The last time is to upload a txt file, this time uploading is a picture. Again, uploading success requires feedback to the client.
Difference:
TXT file opened with Notepad, we can understand, so with a buffer character stream, the channel within the byte stream packaging.
and the picture with Notepad open, we can not understand, so just use buffer byte stream, only need to transfer the bytes in the channel into the efficient stream of words.
Client:
1 Public classClinedemo {2 Public Static voidMain (string[] args)throwsIOException {3 4 //creating a Socket object5Socket s =NewSocket ("172.19.12.233", 10010);6 7 //package picture, picture can only use byte stream, in order to efficient, with buffer bytes Flow8Bufferedinputstream bi =NewBufferedinputstream (NewFileInputStream (9"Java programmer. jpg"));Ten One //wraps a byte stream in a channel into a buffer ABufferedoutputstream bo =NewBufferedoutputstream (S.getoutputstream ()); - - //receiving pictures and sending them to the server the byte[] Bys =New byte[1024]; - intlen = 0;//the actual length of the read, when there is no data, is-1 - while(len = Bi.read (bys))! =-1) { -Bo.write (bys, 0, Len); + Bo.flush (); - } + A // Reminder server has been read completed, terminated at s.shutdownoutput (); - - // receive feedback -InputStream in =S.getinputstream (); - byte[] by =New byte[1024]; - //there must be something in it, no judgment. in intLen1 =In.read (by); -String str =NewString (by,0, len1); to System.out.println (str); + - //Freeing Resources the bi.close (); * s.close (); $ }Panax Notoginseng}
Server:
1 Public classServerdemo {2 Public Static voidMain (string[] args)throwsIOException {3 4 //Create ServerSocket object, listen5ServerSocket SS =NewServerSocket (10010);6 7 //creating a Socket object8Socket s =ss.accept ();9 Ten //stream the bytes in the channel into a buffered byte OneBufferedinputstream bi =NewBufferedinputstream (S.getinputstream ()); A - //Package Picture Catalog -Bufferedoutputstream bo =NewBufferedoutputstream ( the NewFileOutputStream ("Java.jpg")); - - // get the image data and output - byte[] Bys =New byte[1024]; + intLen = 0; - while(len = Bi.read (bys))! =-1) { +Bo.write (bys, 0, Len); A Bo.flush (); at } - - //Feedback to clients -OutputStream op =S.getoutputstream (); -Op.write ("Image upload succeeded". GetBytes ()); - in //Freeing Resources - s.close (); to bo.close (); + - } the}
Java 26-8 Network Programming TCP protocol upload image