Socket communication for Java

Source: Internet
Author: User

   This article explains how to use Java to implement network communication , is a very simple example, I prefer to be able to see the results immediately , so the code to explain the specific details.

Service side :

ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServer {//build server-side     Public Static voidMain (string[] args)throwsIOException {Server server=NewServer (); //Create a server, that is, serverServer.oneserver (); }     Public voidOneserver () {Try{serversocket server=NULL; Server=NewServerSocket (5209); System.out.println ("Server started successfully"); System.out.println ("Waiting for client connections"); //Specifies the port that is bound and listens for this port. Socket Socket=server.accept (); System.out.println ("Listen to the client's connection"); System.out.println ("Connection succeeded"); //call the Accept () method to start listening on the port, waiting for the client to connectString Line; //store data sent by each otherBufferedReader in =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //remove data from the socket object .PrintWriter writer=NewPrintWriter (Socket.getoutputstream ()); //always write data to the socket that you want to pass to each other             while(line = In.readline ())! =NULL) {writer.println ( line+ "Deal by Servet"); //output The string to the clientWriter.flush (); //refreshes the output stream so that the client receives the string immediatelySystem.out.println ("Client:" +Line ); //reads a string from the client and prints it to the standard output}//Continue looping//Close ResourceWriter.close ();//close the socket output streamIn.close ();//close the socket input streamSocket.close ();//Close SocketServer.close ();//shutting down the server}Catch(Exception e) {//error, printing error messageSystem.out.println ("Error." +e); }    }}

Client :

ImportJava.net.Socket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;Importjava.net.InetAddress;ImportJava.net.Socket;ImportJava.net.URL; Public classClient {//Build the client     Public Static voidMain (string[] args)throwsIOException {Try {            //Create a client socket, specify the server address and Port//Socket socket=new Socket ("127.0.0.1", 5200);SYSTEM.OUT.PRINTLN ("Client startup succeeded"); Socket Socket=NewSocket ("192.168.69.183", 5209); System.out.println ("Successful request to server Port 5209"); BufferedReader BR=NewBufferedReader (NewInputStreamReader (system.in)); //The data is read by the system standard input device, which is written to the other's socket by writer.PrintWriter Write=NewPrintWriter (Socket.getoutputstream ()); //always write data to the socket to pass to each otherBufferedReader in=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //remove data from the socket object .String ReadLine; ReadLine= Br.readline ();//reads a string from the system standard input             while(!readline.equals ("End")) {                //stop Looping if the string read in from standard input is "end"write.println (ReadLine); //output A string read from the system standard input into the other's socketWrite.flush (); //print out the data sent by the other person.System.out.println ("Server:" +in.readline ()); //reads a string from the server and prints it to the standard outputReadLine = Br.readline ();//reads a string from the system standard input}//Continue looping//Close ResourceWrite.close ();//close the socket output stream//in.close ();//close the socket input streamSocket.close ();//Close SocketBr.close (); } Catch(Exception e) {System.out.println ("Can not listen to:" + E);//error, printing error message        }    }}

  The function we want to implement here is that the client enters a string from the keyboard, sends it to the server, and returns to the client after the service-side processing (the original string followed by the "deal by Servet") is completed . I'm using eclipse, it's best to open two eclipse a running client a running server. first open the server, then open the client (the order can not be wrong), the client input hello, the server returned hello deal by servers:

  

See the results then you can analyze the entire communication process.

Put a socket communication model first:

  

  

  Three parts: establish the connection, start the communication, disconnect the connection .

To establish a connection: we'll know a little bit about it. The process of establishing a connection is preceded by a server, and then client clients can find it, so start the service side first. Maybe we think that the server is a very mysterious thing, actually not, look at our example of the service side of the code:

  

  New server, but this server new comes out and does nothing, we need to call him inside the method to let this server can run . So write a oneserver method that the server object calls this method to start running.

So what did the server do when it was running? Looking at the model above, the server runs three things: Connect, transfer data, disconnect.

Look at the code in Oneserver, first create a ServerSocket object, which has a parameter 5209:

  

  ServerSocket is specifically used to create server objects, where parameter 5209 means that the server can be connected via port 5209, that is, Port 5209 is bound to the created ServerSocket object . But this binding only establishes a channel between the server and the port, we also need to be able to let the server know that there is data from the outside to this port, and because the port cannot hold the data, it needs a socket to temporarily hold the data . So with the following monitoring:

  

  

here, the server is up and running, and the client can connect.

  When the client is started, the client connects to the server via the socket, specifying the IP and port number:

  

  The client runs here to indicate that the connection to the server has been completed :

  

  

  After the connection succeeds, the data is transferred, and the client creates three objects:

  

  BR reads the data to be transmitted from the keyboard, write writes the data to the socket to be passed to the server, and in the data returned from the server is fetched from the socket object.

  The server creates two objects:

  

  Write writes the data to the socket to be passed back to the client, in which the data from the client is removed from the socket object.

The preparation for data transfer here is complete and the next step is data transfer.

The client reads a string (hello) from the keyboard, which is read in by BR:

  

  

  

  

  The client then determines whether the end, not end, continues. Through the client's write, writes the content in the ReadLine to the other side (the service side) socket , simultaneously uses the Write flush method to inform the service side , lets the service side immediately know has the data:

  

After the service side hears the port has data, through in receives the client to send the data, and then turns into the string, then processes the string (plus deal by server) and writes to the client's socket , also calls the writer's The Flush method notifies the client :

  

  Running here, the server has processed and returned the data sent by the client, and the returned data can be seen in the client's console:

  

  The server prints out the data from the client in its own console:

  

  

  The entire delivery process ends, and if the input string is end, then the while loop jumps out, and the client server shuts down the resource separately:

  

  

  Here, the whole process is over.

Then text the whole process, the server starts--the server creates the socket and listens --the client initiates--the client creates the socket connection server --The connection completes--the client enters the data and writes to the socket on the service side sent to the server--the server receives the data from the client--processing the data-- and putting it in the client's socket --The client takes the data in its socket --print--The two sides are disconnected.

  

  

Socket communication for Java

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.