Java Sockets (socket) instance

Source: Internet
Author: User

Client socket

Process:

1. Connecting to a remote host

2. Send data

3. Receive data

4. Close the stream and socket connection

Instance:

ImportJava.io.*;ImportJava.net.Socket;Importjava.util.Date;/*** Created by CLY on 2017/7/11.*/ Public classClientsocket { Public Static voidMain (string[] arg) {intPort = 233;//port number of the service-side socket with which it is connectedString host = "127.0.0.1";//The service-side socket IP address to which it is connectedSocket socket =NULL; Try {            //creates a socket connection that, before the socket constructor returns, establishes a connection to the remote host and throws an exception if it fails to connect. Socket =NewSocket (host, Port); //gets the output stream, sending the current time to the server sideOutputStream OutputStream =Socket.getoutputstream (); Writer writer=NewOutputStreamWriter (OutputStream); String now_date=NewDate (). toString (); Writer.write ("Client current time is--" +now_date);            Writer.flush (); ////closes the client's output stream. Equivalent to adding an end tag to the stream-1. This way the Realine method of the input stream of the server reads a-1 and then ends the ReadLine method. Socket.shutdownoutput (); //gets the input stream and reads the server-side response informationInputStream inputstream=Socket.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (InputStream)); String Server_info=NULL;  while((Server_info=br.readline ())! =NULL) {System.out.println ("The value passed by the server:" +server_info); }        } Catch(IOException e) {e.printstacktrace (); } finally {            //If the socket is not NULL, release it            if(socket!=NULL){                Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }    }}

Service-side sockets

Process:

1. Binding port

2. Listening to inbound data

3. Accept the connection from the remote machine on the bound port

4. Receive data

5. Send data

6. Close the stream and socket connection

Instance:

ImportJava.io.*;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.util.Date;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Created by CLY on 2017/7/11.*/ Public classmyServerSocket { Public Static voidMain (string[] arg) {/*** According to the TCP protocol, the so-called socket (socket) refers to a combination of "IP address + port". * and each host's IP address is OK, do not need us to specify, * so the first step in building a server socket is to determine the port*/        Try {            intPort = 233;//Port number            intQueuelength = 50;//Maximum Inbound ConnectionsInetAddress bindaddress = Inetaddress.getbyname ("127.0.0.1");//only the specified port of the IP is listeningExecutorservice pool = Executors.newfixedthreadpool (50);//Create a thread pool with a maximum capacity of 50, and assign one to each inbound connection. //create a server socket with a port of "233"ServerSocket ServerSocket =NewServerSocket (port); //create a server socket with port 233, and the queue can hold up to 50 inbound connections at a time//ServerSocket serversocket = new ServerSocket (port,queuelength); //Assuming that a host has multiple IP addresses, the server socket listens on the specified port on all IP addresses by default, but can specify that it listens on only the port of the specified IP. //ServerSocket serversocket = new ServerSocket (port,queuelength,bindaddress);             while(true){                //the Accept () call is blocked until a client connects to the specified socket port.                 FinalSocket connection =serversocket.accept (); //the thread pool takes a thread to handle the socket connection. The main program then runs the next loop and continues to wait for the next client access. Pool.execute (NewRunnable () { Public voidrun () {Try {                            //read from the input stream gets the value that the client passed overInputStream inputstream=Connection.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (InputStream)); String Client_info=NULL;  while((Client_info=br.readline ())! =NULL) {System.out.println ("The value the client passed over:" +client_info); }                            //test: Returns the current time to the client in the write streamWriter writer =NewOutputStreamWriter (Connection.getoutputstream ()); String Nowdata=NewDate (). toString (); Writer.write ("Service-side current time is--" +nowdata);                        Writer.flush (); } Catch(IOException e) {e.printstacktrace (); } finally {                            Try {                                //Close the socket connectionConnection.close (); } Catch(IOException e) {e.printstacktrace ();            }                        }                    }                }); }        } Catch(IOException e) {e.printstacktrace (); }    }}

Java Sockets (socket) instance

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.