Java Learning Note 53 (Network Programming: TCP protocol Case)

Source: Internet
Author: User

A simple case

Client:

 Packagedemo;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket; Public classTCPClient { Public Static voidMain (string[] args)throwsIOException {Socket Socket=NewSocket ("127.0.0.1", 7000); OutputStream out=Socket.getoutputstream (); Out.write ("Hello". GetBytes ()); InputStream in=Socket.getinputstream (); byte[] data =New byte[1024]; intLen =in.read (data); System.out.println (NewString (data, 0, Len));    Socket.close (); }}
View Code

Server-side:

 Packagedemo;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTCPServer { Public Static voidMain (string[] args)throwsIOException {serversocket server=NewServerSocket (7000); Socket Socket=server.accept (); InputStream in=Socket.getinputstream (); byte[] data =New byte[1024]; intLen =in.read (data); System.out.println (NewString (data, 0, Len)); OutputStream out=Socket.getoutputstream (); Out.write (Receive. GetBytes ());        Socket.close ();    Server.close (); }}
View Code

Start the server side, then start the client, server-side print: Hello, and then the client prints: Received

Note that the flow object is differentiated here

Next in this case based on a picture upload case

The essence of image upload is file copy

Client:

 PackageDemo1;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket; Public classTCPClient { Public Static voidMain (string[] args)throwsIOException {Socket Socket=NewSocket ("127.0.0.1", 7000); OutputStream out=Socket.getoutputstream (); FileInputStream FIS=NewFileInputStream ("D:\\666.jpeg"); intLen = 0; byte[] bytes =New byte[1024];  while(len = fis.read (bytes))! =-1) {out.write (bytes,0, Len);        } socket.shutdownoutput (); //server-side read-1, does not terminate, call this method can terminateInputStream in =Socket.getinputstream (); Len=in.read (bytes); System.out.println (NewString (Bytes, 0, Len));        Fis.close ();    Socket.close (); }}
View Code

Server-side:

 PackageDemo1;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.Random; Public classTCPServer { Public Static voidMain (string[] args)throwsIOException {serversocket server=NewServerSocket (7000); Socket Socket=server.accept (); InputStream in=Socket.getinputstream (); File Upload=NewFile ("D:\\upload"); if(!upload.exists ())        {Upload.mkdirs (); } String filename= System.currenttimemillis () +NewRandom (). Nextint (999999) + ". JPEG"; FileOutputStream Fos=NewFileOutputStream (upload + file.separator +filename); //here is the problem of dealing with the names of pictures        byte[] bytes =New byte[1024]; intLen = 0;  while(len = in.read (bytes))! =-1) {fos.write (bytes,0, Len); } socket.getoutputstream (). Write ("Upload succeeded". GetBytes ());        Fos.close ();        Socket.close ();    Server.close (); }}
View Code

If multiple clients are uploading together, a multi-threading technique is required, with each client occupying one thread

Client does not need to modify

Server-side:

 PackageDemo1;Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTCPServer { Public Static voidMain (string[] args)throwsIOException {serversocket server=NewServerSocket (7000);  while(true) {Socket Socket=server.accept (); NewThread (NewUpload (socket)). Start (); }    }}
View Code
 PackageDemo1;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.Random; Public classUploadImplementsRunnable {Privatesocket socket;  PublicUpload (socket socket) { This. Socket =socket; }     Public voidrun () {Try{InputStream in=Socket.getinputstream (); File Upload=NewFile ("D:\\upload"); if(!upload.exists ())            {Upload.mkdirs (); } String filename= System.currenttimemillis () +NewRandom (). Nextint (999999) + ". JPEG"; FileOutputStream Fos=NewFileOutputStream (upload + file.separator +filename); //here is the problem of dealing with the names of pictures            byte[] bytes =New byte[1024]; intLen = 0;  while(len = in.read (bytes))! =-1) {fos.write (bytes,0, Len); } socket.getoutputstream (). Write ("Upload succeeded". GetBytes ());            Fos.close ();        Socket.close (); } Catch(IOException ex) {System.out.println (ex); }    }}
View Code

Java Learning Note 53 (Network Programming: TCP protocol Case)

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.