Learn Java Socket

Source: Internet
Author: User

Java Socket Programming

For Java socket programming, there are two concepts, one is serversocket, one is socket. A connection is made through the socket between the server and the client, and they can then communicate. First ServerSocket will listen to a port on the server, and when it discovers that the client has a socket to try to connect it, it will accept the socket's connection request and establish a corresponding socket on the server side to communicate with it. This will have two sockets, the client and the server each one.

For the communication between the socket is actually very simple, the server to the socket output stream inside the write something, the client can pass the socket input stream to read the corresponding content. Socket and socket is two-way connectivity, so the client can also to the corresponding socket output stream inside write things, and then the corresponding socket of the service side of the input stream can read the corresponding content. Here are some examples of server-side communication with clients: 1, client write service-side read

Service-side code

  Java code    public class server {           Public static void main (string args[])  throws IOException {         //for the sake of simplicity, all the exception information is thrown out          int  port = 8899;         //defines a serversocket listener on port 8899           serversocket server = new serversocket (port);          //server attempts to receive connection requests from other sockets, the Accept method of the server is blocked          socket socket = server.accept ();          //with the client to establish a good connection, we can get the socket inputstream, and read from the client sent over the information.          reader reader = new inputstreamreader ( Socket.getinputstream ());         char chars[] = new char[64];          int len;         stringbuilder sb = new  stringbuilder ();         while  ((Len=reader.read (chars))  != -1)  {            sb.append (new  String (Chars, 0, len));         }          system.out.println ("from client: "  + SB);          reader.close ();         socket.close ();          server.close ();      }         }  

The operation of the server to read data from the socket's InputStream is also blocked, and if the data is not read from the input stream the program will remain there until the client writes the data to the socket's output stream or closes the output stream of the socket. Of course, the same is true for socket sockets for clients. After the operation is complete, remember to close the corresponding resource before the end of the program, that is, close the corresponding IO stream and socket.

Client Code Java code    public class client {          public  static void main (string args[])  throws Exception {          //for simplicity, all the anomalies are thrown directly out          string host  =  "127.0.0.1"   //IP address of the server to be connected          int  port = 8899;   //the corresponding listening port          //for the server to be connected Connect with the service side          socket client = new socket (host,  port);         //can write data to the server after the connection is established           writer writer = new outputstreamwriter (Client.getOutputStream ());          writer.write ("hello server.");         &nbsP;writer.flush ()//write flush         writer.close ();         client.close ();      }         }  

For the client to the socket output stream inside the write data to the server to pay attention to a point, if the program is not corresponding to the output stream after the shutdown, but to do other blocking operations (such as from the input stream read data), remember to flush, only so that the server can receive the data sent by the client , or it may cause both sides to wait indefinitely. We'll talk about this later when we talk about both the client and the server while reading and writing.

2, the client and the server to read and write at the same time

I have already said that the socket is two-way communication, it can receive data, but also can send data.

Service-side code

  Java code    public class server {           Public static void main (string args[])  throws IOException {         //for the sake of simplicity, all the exception information is thrown out          int  port = 8899;         //defines a serversocket listener on port 8899           serversocket server = new serversocket (port);          //server attempts to receive connection requests from other sockets, the Accept method of the server is blocked          socket socket = server.accept ();          //with the client to establish a good connection, we can get the socket inputstream, and read from the client sent over the information.          reader reader = new inputstreamreader ( Socket.getinputstream ());         char chars[] = new char[64];          int len;         stringbuilder sb = new  stringbuilder ();         while  ((Len=reader.read (chars))  != -1)  {            sb.append (new  String (Chars, 0, len));         }          system.out.println ("from client: "  + SB);          //Read and write a sentence          writer writer =  new outputstreamwriter (Socket.getoutputstream ());          Writer.write ("hello client.");          writer.flush ();      &Nbsp;  writer.close ();         reader.close ();         socket.close ();          Server.close ();      }        }  

        

In the above code, we first read the data from the input stream, then we write the data to the client in the output stream, then close the corresponding resource file. And actually the code might not work the way we thought it would, because reading data from an input stream is a blocking operation, the loop body is executed when the data is read in the same while loop, or it blocks so that the subsequent write operation is never executed. The while loop jumps out unless the client's corresponding socket closes and the blocking stops. The solution to a situation that could never be performed is if the while loop needs to jump in conditionally, looking at the above code, in the constantly changing only the length of Len and read the data, Len is no longer available, the only use is to read the data. In this case, we usually agree to a closing tag, when the data sent by the client contains a closing tag to indicate that the current data has been sent, and this time we can jump out of the loop. Then the improved code would look like this: Java code    public class server {           public static void main (string args[])  throws ioexception {          //All exception information is thrown out for simplicity           int port = 8899;         // Define a ServerSocket listener on port 8899          serversocket server =  new serversocket (port);         //server attempts to receive other socketsConnection requests, the server's accept method is blocked          Socket socket =  Server.accept ();         //the connection to the client, we can get the socket inputstream, and read the information sent from the client.          reader reader = new inputstreamreader ( Socket.getinputstream ());         char chars[] = new  char[64];         int len;          stringbuilder sb = new stringbuilder ();          String temp;         int index;         while  ((Len=reader.read (chars))  != -1)  {            temp = new string (Chars, 0, len );             if  ((Index = temp.indexof ("EOF")  !=  -1)  {//ends the reception                when it encounters EOF  sb.append (temp.substring (0, index));                break;            }            sb.append (temp);          }         system.out.println ("from client: "  + SB);         //write a sentence after reading           writer writer = new outputstreamwriter (Socket.getoutputstream ());         writer.write ("hello client.");          writer.Flush ();         writer.close ();          reader.close ();         socket.close ();          server.close ();      }         }  

In the preceding code, when the server reads the end tag sent by the client, that is, "EOF", it ends the receipt of the data and terminates the loop so that subsequent code can continue.

Client Code Java code    public class client {          public  static void main (string args[])  throws Exception {          //for simplicity, all the anomalies are thrown directly out         string host =   "127.0.0.1"   //IP address of the server to be connected         int port =  8899;   //to connect to the service end of the corresponding listening port         //with the server to establish a connection         socket client = new socket (Host, port);         //can write data to the server after the connection is established         Writer  Writer = new outputstreamwriter (Client.getoutputstream ());          writer.write ("Hello server.");          writer.flush ();        //read after writing         reader reader  = new inputstreamreader (Client.getinputstream ());          char chars[] = new char[64];         int  len;         StringBuffer sb = new  StringBuffer ();         while  ((Len=reader.read (chars))  !=  -1)  {            sb.append (new string ( Chars, 0, len));         }          system.out.println ("from server: "  + SB);          writer.close ();         reader.close ();        &nbSp;client.close ();      }        }  

        in the above code we first send a piece of data to the server, and then read the data returned by the server, which, like the previous server, may cause the program to hang there. Never jumps out of a while loop. This code together with the first piece of code on the server just let us analyze the server is always there to receive data, never jump out of the while loop, there is no later server to return data to the client, the client will not be able to receive the data returned by the server. Solution such as the second paragraph of the server code, after the client sent the data, to the output stream inside the write to the end tag to tell the service end of the data has been sent, the same server returned data after the end of a tag to tell the client. Then the modified client code should look like this: Java code    public class client {           public static void main (string args[])  throws Exception {          //For simplicity, all exceptions are thrown directly out         string  host =  "127.0.0.1"   //IP address of the server to be connected         int  port = 8899;   //the corresponding listening port         //for the server to be connected Establish a connection with the server         socket client = new socket (host,  Port);         //The connection can be made to write data to the server         Writer writer = new  OutputStreamWriter (Client.getoutputstream ());         writer.write (" Hello server. ");          writer.write ("EOF");          writer.flush ();         //after the completion of the read operations          reader reader = new inputstreamreader (Client.getinputstream ());         char chars[] = new char[64];          int len;         STRINGBUFFER SB  = new stringbuffer ();         String temp;          int index;         while &nbsp ((Len=reader.read (chars))  != -1)  {             temp = new string (Chars, 0, len);             if  ((Index = temp.indexof ("EOF")  != -1)  {       

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.