Advertisement
obernardovieira

Java Send/Receive File Sockets

Dec 13th, 2016
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. public class SocketFileExample {
  2.     static void server() throws IOException {
  3.         ServerSocket ss = new ServerSocket(3434);
  4.         Socket socket = ss.accept();
  5.         InputStream in = new FileInputStream("send.jpg");
  6.         OutputStream out = socket.getOutputStream();
  7.         copy(in, out);
  8.         out.close();
  9.         in.close();
  10.     }
  11.  
  12.     static void client() throws IOException {
  13.         Socket socket = new Socket("localhost", 3434);
  14.         InputStream in = socket.getInputStream();
  15.         OutputStream out = new FileOutputStream("recv.jpg");
  16.         copy(in, out);
  17.         out.close();
  18.         in.close();
  19.     }
  20.  
  21.     static void copy(InputStream in, OutputStream out) throws IOException {
  22.         byte[] buf = new byte[8192];
  23.         int len = 0;
  24.         while ((len = in.read(buf)) != -1) {
  25.             out.write(buf, 0, len);
  26.         }
  27.     }
  28.  
  29.     public static void main(String[] args) throws IOException {
  30.         new Thread() {
  31.             public void run() {
  32.                 try {
  33.                     server();
  34.                 } catch (IOException e) {
  35.                     e.printStackTrace();
  36.                 }
  37.             }
  38.         }.start();
  39.  
  40.         client();
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement