1. The TCP protocol uploads images and gives feedback:
(1) Client:
1 Packagecn.itcast_13;2 3 ImportJava.io.BufferedInputStream;4 ImportJava.io.BufferedOutputStream;5 ImportJava.io.FileInputStream;6 Importjava.io.IOException;7 ImportJava.io.InputStream;8 ImportJava.net.Socket;9 Ten Public classuploadclient { One Public Static voidMain (string[] args)throwsIOException { A //creating a Client socket object -Socket s =NewSocket ("192.168.12.92", 19191); - the //Package picture File -Bufferedinputstream bis =NewBufferedinputstream (NewFileInputStream ( -"Brigitte. jpg")); - //flow within the encapsulated channel +Bufferedoutputstream BOS =NewBufferedoutputstream (S.getoutputstream ()); - + byte[] Bys =New byte[1024]; A intLen = 0; at while(len = Bis.read (bys))! =-1) { -Bos.write (bys, 0, Len); - Bos.flush (); - } - - s.shutdownoutput (); in - //Read Feedback toInputStream is =S.getinputstream (); + byte[] Bys2 =New byte[1024]; - intLen2 =Is.read (BYS2); theString client =NewString (BYS2, 0, len2); * System.out.println (client); $ Panax Notoginseng //Freeing Resources - bis.close (); the s.close (); + } A}
(2) Service side:
1 Packagecn.itcast_13;2 3 ImportJava.io.BufferedInputStream;4 ImportJava.io.BufferedOutputStream;5 ImportJava.io.FileOutputStream;6 Importjava.io.IOException;7 ImportJava.io.OutputStream;8 ImportJava.net.ServerSocket;9 ImportJava.net.Socket;Ten One Public classUploadserver { A Public Static voidMain (string[] args)throwsIOException { - //Create a Server socket object -ServerSocket SS =NewServerSocket (19191); the - //Listening for client connections -Socket s =ss.accept (); - + //Package Channel Internal flow -Bufferedinputstream bis =NewBufferedinputstream (S.getinputstream ()); + //Package picture File ABufferedoutputstream BOS =NewBufferedoutputstream ( at NewFileOutputStream ("Mn.jpg")); - - byte[] Bys =New byte[1024]; - intLen = 0; - while(len = Bis.read (bys))! =-1) { -Bos.write (bys, 0, Len); in Bos.flush (); - } to + //Give a feedback -OutputStream OS =S.getoutputstream (); theOs.write ("Image upload succeeded". GetBytes ()); * $ bos.close ();Panax Notoginseng s.close (); - } the}
Java Basic Knowledge Enhancement Network programming note 13:tcp TCP protocol upload images and give feedback