Socket usage Detailed

Source: Internet
Author: User

In client/server communication mode, the client needs to proactively create a socket (socket) with the server, which receives a request from the client and creates a socket attached to the client.

Scoket can be seen as a transceiver for both ends of the communication, both the server and the client are sending and receiving data via Scoket ~ ~ ~

A: First introduce the construction method of Scoket:

Overloading of constructor methods:

 socket () Socket (inetaddress address,  int  port) throws   Unknowhostexception, Ioexceptionsocket (inetaddress address,  int  Port, InetAddress localaddr, int  localport)  Ioexceptionsocket (String host,  int  Port) throws   Unknowhostexception, Ioexceptionsocket (String host,  int  Port, inetaddress localaddr, int  LocalPort) throws  IOException 

1: Parse: In addition to the first non-parametric construction method, the rest of the construction methods are trying to create a connection with the server, if the connection succeeds, the socket object is returned, and if for some reason the connection fails, an exception is thrown ...

2: Use the parameterless construction method to set the timeout time to wait for the connection to be established:

New Socket ();   New Inetsocketaddress ("localhost", 8000);   60000);  // the timeout to wait for the connection to be established is 1 minutes

The above code is used to connect to a server program that listens on 8000 ports on the local machine, and the maximum time to wait for a connection is 1 minutes. If the connection succeeds within 1 minutes, the Connet () method returns smoothly; If an exception occurs within 1 minutes, the exception is thrown; If after 1 minutes, there is no successful connection and no other exception, then Sockettimeoutexception will be thrown. The Socket class's connect (socketaddress endpoint, int timeout) method is responsible for connecting to the server, the parameter endpoint specifies the server's address, and the parameter timeout sets the timeout data, in milliseconds. If the parameter timeout is set to 0, it means that it will never time out and the default will not time out.

3: Set the server's address

In addition to the first constructed method without parameters, the other constructor methods need to set the server's address in the parameters, including the server's IP address or hostname, and the port:

int port)              // The first parameter address indicates the IP address of the host  int port)                              //  The first parameter, host, indicates the name of the hostname

Two. Getting the socket information

A socket object contains both the IP address and port information of the remote server, as well as the client's local IP address and port information. In addition, the output stream and input stream can be obtained from the socket object, respectively, to send data to the server, and to receive data from the server side. The following methods are used to obtain information about the socket.

Getinetaddress (): Gets the IP address of the remote server. Getport (): Gets the port of the remote server. Getlocaladdress (): Gets the client's local IP address. Getlocalport (): Gets the client's local port. getInputStream (): Gets the input stream. If the socket is not connected, or has been shut down, or the input stream has been closed through the Shutdowninput () method, this method throws Ioexception.getoutputstream (): The output stream is obtained, and if the socket is not connected, Or it has been closed, or the output stream has been closed through the Shutdownoutput () method, then this method throws IOException.

Three. Close the socket

When the client communicates with the server, the socket should be closed in time to release the various resources, including ports, that the socket occupies. The close () method of the socket is responsible for closing the socket. When a socket object is closed, it can no longer do I/O through its input stream and output stream, otherwise it will cause ioexception.

In order to ensure that the operation to close the socket is always executed, it is strongly recommended that this operation be placed in the finally code block:

Socket socket =NULL; Try{Socket=NewSocket (www.javathinker.org,80); //perform operations that receive and send data        .........   }Catch(IOException e) {e.printstacktrace (); }finally{        Try{             if(Socket! =NULL) Socket.close (); }Catch(IOException e) {e.printstacktrace ();} }

The Socket class provides 3 state test methods.

IsClosed (): Returns True if the socket is already connected to the remote host and is not turned off, otherwise false. IsConnected (): Returns True if the socket was connected to a remote host, otherwise false. Isbou nd (): Returns True if the socket is already bound to a local port, otherwise false.

Five. Setting the socket options

The Socket has several options.

Tcp_nodelay: Indicates that data is sent immediately. SO_RESUSEADDR: Indicates whether the local address that the socket is bound to is allowed to be reused. So_timeout: Represents the wait time-out data when receiving data. So_linger: Indicates whether to close the underlying socket.so_snfbuf immediately when the close () method of the socket is executed: the size of the buffer that represents the data being sent. SO_RCVBUF: Represents the size of the buffer that receives the data. So_keepalive: Indicates whether to automatically turn off a socket that is idle for a long time. Oobinline: Indicates whether to support sending a byte of TCP emergency data.

Socket Usage Detailed

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.