The difference between the "Android note" ServerSocket and the socket

Source: Internet
Author: User

1 ServerSocket class
Create a ServerSocket class and establish a listening service at the specified port of the computer on which the statement is run, such as:
ServerSocket mylistener=new ServerSocket (600);
This specifies that the port that provides the listening service is 600, a computer can provide multiple services at the same time, these different services are differentiated by port number, and different services are provided on different port numbers. To listen for possible client requests at any time, execute the following statement:
Socket Linksocket=mylistener. Accept ();
The statement invokes the Accept () method of the ServerSocket object, which executes the server-side program in a wait state, and the program blocks until a request is captured from the client side. and returns a Socket object that is used to communicate with the client link-socket. Thereafter, the server program can read and write data to the remote client as long as the data is read and written to the socket object. To end the listener, close the ServerSocket object:
MyListener. Close ();
2 Socket Class
When the client program needs to obtain information and other services from the server side, a socket object should be created:
Socket mysocket=new socket ("Servercomputername", 600);
The constructor for the socket class has two parameters, the first parameter is the host address of the server computer to which you want to connect, and the second parameter is the port number on the server machine that provides the service.
Once the socket object is successfully established, a connection can be established between the client and the server, and the data is passed between the two endpoints through this connection. Using the Socket class method Getoutputstream () and getInputStream () respectively obtain the input/output stream to read and write data to the socket, and finally return the data read from the server side back to the server side.
When the communication between the server and client ends, you can call the close () method of the socket class to close the socket and remove the connection.

ServerSocket generally only used to set the port number and monitoring, the real communication is the server-side socket and client socket, after the ServerSocket to accept, will be the active transfer.

1. Server-side programming
On the server side, use the ServerSocket class's constructor serversocket (int port) to create an object of the ServerSocket class, the port parameter delivery port, which is the port on which the server listens for connection requests. If an error occurs at this point, the IOException exception object is thrown, otherwise the ServerSocket object is created and the readiness to receive the connection request begins.
The service program starts with the Accept () method that calls ServerSocket until the connection is established. After the connection is established, accept () returns a recently created socket object that binds the client's IP address or port number.
2. Client Programming
When the client program needs to communicate with the server program, it needs to create a socket object on the client. The socket class has a constructor socket (inetaddress Addr,int port) and a socket (String host,intport), and two constructors have created a socket-based streaming socket for the connection server-side flow socket. For the first Inetad-dress subclass object, the IP address of the server host is obtained through the addr parameter, and for the second function the host parameter package is assigned to the InetAddress object, if no IP address matches the host parameter, Then the unknownhostexception exception object is thrown. Two functions are given the port number of the server via the parameter port. Assuming the connection has been established, the network API will bundle the client's IP address and any port number in a socket-based streaming socket, otherwise two functions will throw a IOException object.
If a socket object is created, it can be obtained from the service program via the Get-inputstream () method, or the output stream can be sent by calling the Getoutputstream () method. After the read-write activity is completed, the client program calls the close () method to close the stream and stream the socket.

Elementary procedures to explain:

Server-side code:

1;2;3;4;5 6  7 8  Public classMyserver {9 Ten //establish the ServerSocket and set its port number One     PrivateServerSocket SS; A     -      Public Static Final intport=8962; -      the      PublicMyserver () { -      -     Try{ -      +ss=NewServerSocket (port); -      +}Catch(IOException e) { A      at e.printstacktrace (); -     } -      -     } -      Public voidSetConnection ()throwsioexception{ -    //Create a server-side socket in Socket S; - outputstream os; to     Try{//serversocke.accept () t returns a socket object +  -s=ss.accept (); theos=S.getoutputstream (); *Os.write ("Hello". GetBytes ()); $ os.close ();Panax Notoginseng s.close (); -}Catch(IOException e) { the      + e.printstacktrace (); A     } the      +     } -  $      Public Static voidMain (string[] args)throwsIOException { $      -Myserver ms=NewMyserver (); - ms.setconnection (); the    - }Wuyi  the}

Client code:

1;2;3;4;5;6 7  8 9  Public classmyclient {Ten        Public Static FinalString ip= ""; One        Public Static Final intport=8962; A       PrivateSocket S; -  -        PublicMyClient ()throwsioexception{ the Try{ -s=NewSocket (ip,port); -  -}Catch(IOException e) { +    - e.printstacktrace (); + } A       } at        -        Public voidSetConnection ()throwsioexception{ -         - InputStream is; -         -     Try{ inis=S.getinputstream (); -BufferedReader br=NewBufferedReader (NewInputStreamReader (IS)); to      + System.out.println (Br.readline ()); -      the}Catch(IOException e) { *      $ e.printstacktrace ();Panax Notoginseng     }    -         the        +       } A  Public Static voidMain (String args[])throwsioexception{ the    +MyClient mc=Newmyclient (); - mc.setconnection (); $    $ } -}

Reference Original:

The difference between the "Android note" ServerSocket and the socket

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: 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.