Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

Sockets

Hello all,

Can anyone give me the code on how to send a file or just stream 2MB over a socket??

Thanks
0
aknight_sa
Asked:
aknight_sa
1 Solution
 
CEHJCommented:
 class FileSender {
    final int BUF_SIZE = 4096;
    Socket socket;
    OutputStream out;

    public FileSender(Socket socket) {
      this.socket = socket;
    }

    public boolean sendFile(String fileName) {
      FileInputStream from = null;
      try {
        int bytesRead = 0;
        from = new FileInputStream(fileName);
        out = new BufferedOutputStream(socket.getOutputStream());
        byte[] buffer = new byte[BUF_SIZE];
        while((bytesRead = from.read(buffer)) != -1) // Read bytes until EOF
          out.write(buffer, 0, bytesRead);            //   write bytes
      }
      // Always close the streams, even if exceptions were thrown
      catch (IOException e) {
        return false;
      }
      finally {
        if (from != null) try { from.close(); } catch (IOException e) { ; }
        if (out != null) try { out.close(); } catch (IOException e) { ; }
        if (socket != null) try { socket.close(); } catch (IOException e) { ; }
      }
      return true;
    }
  }
}
0
 
Ajay-SinghCommented:
The code below reads data from a file and writes it over a socket:-

InputStream in = new FileInputStream("file");
OutputStream out = socket.getOuputStream();
final int CHUNK_SIZE = 1024;
byte buff[] = new byte[CHUNK_SIZE];
int read = in.read(buff, 0, CHUNK_SIZE);
while(read>0) {
    out.write(buff, 0, read);
    read = in.read(buff, 0, CHUNK_SIZE);
}
in.close();
out.close();
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now