Java sending and processing ing file (byte []) over sockets

Source: Internet
Author: User
 

Server

publicclassServer{/** * @param args the command line arguments */

public static void main(String[] args)throwsIOException{
ServerSocket serverSocket =null;try{ serverSocket =newServerSocket(4444);
}catch(IOException ex){
System.out.println("Can't setup server on this port number. ");
}
Socket socket =null;
InputStream is =null;
FileOutputStream fos =null;
BufferedOutputStream bos =null;
int bufferSize =0;try{ socket = serverSocket.accept();}
catch(IOException ex){
System.out.println("Can't accept client connection. ");
}try{ is = socket.getInputStream(); bufferSize = socket.getReceiveBufferSize();
    System.out.println("Buffer size: "+ bufferSize);
}catch(IOException ex){System.out.println("Can't get socket input stream. ");
}try{ fos =newFileOutputStream("M:\\test2.xml"); bos =newBufferedOutputStream(fos);
  }catch(FileNotFoundException ex){
    System.out.println("File not found. ");
  }
  byte[] bytes =newbyte[bufferSize];
  int count;
  while((count = is.read(bytes))>0){ bos.write(bytes,0, count);
} bos.flush(); bos.close(); is.close(); socket.close(); serverSocket.close();}

}

And the client

publicclassClient{/** * @param args the command line arguments */

public static void main(String[] args)throwsIOException{
  Socket socket =null;
  String host ="127.0.0.1"; socket =newSocket(host,4444);
  File file =newFile("M:\\test.xml");// Get the size of the file
  long length = file.length();
  if(length >Integer.MAX_VALUE){
    System.out.println("File is too large.");
  }
  byte[] bytes =newbyte[(int) length];
  FileInputStream fis =newFileInputStream(file);
  BufferedInputStream bis =newBufferedInputStream(fis);
  BufferedOutputStream out =newBufferedOutputStream(socket.getOutputStream());
  int count;
  while((count = bis.read(bytes))>0){ out.write(bytes,0, count);
  } out.flush(); out.close(); fis.close(); bis.close(); socket.close();}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.