Chapter 1 socket usage in Java learning Summary

Source: Internet
Author: User
Tags set socket
I. Construct a socket

The socket constructor has the following methods:

(1) socket ()

(2) socket (inetaddress address, int port) throws unknownhostexception, ioexception

(3) socket (inetaddress address, int port, inetaddress localaddr, int localport) throws ioexception

(4) socket (string host, int port) throws unknownhostexception, ioexception

(5) socket (string host, int port, inetaddress localaddr, int localport) throws ioexception

The usage of each constructor is as follows:

1. Set the timeout time for the connection to be established:

Socket socket = new socket ();

Socketaddress remoteaddr = new inetsocketaddress ("localhost", 8000 );

// Wait until the connection is established for 1 minute

Socket. Connect (remoteaddr, 60000 );

2. Set the server address:

Socket (inetaddress address, int port)

Socket (string host, int port)

The inetaddress class indicates the IP address. Its usage is as follows:

// Return the IP address of the local host

Inetaddress addr1 = inetaddress. getlocalhost ();

// Return the IP address representing "222.34.5.7"

Inetaddress addr2 = inetaddress. getbyname ("222.34.5.7 ");

// Return the IP address of the domain name "www.javathinker.org"

Inetaddress addr3 = inetaddress. getbyname ("www.javathinker.org ");

3. Set the client address:

A socket object contains both the IP address and port information of the remote server and the IP address and port information of the local client. By default, the Client IP address comes from the customerProgramHost. The client port is randomly allocated by the operating system. The socket class also has two constructor methods that allow you to explicitly set the IP address and port of the client:

Socket (inetaddress address, int port,Inetaddress localaddr, int localport) Throws ioexception

Socket (string host, int port,Inetaddress localaddr, int localport) Throws ioexception

4. exceptions that a customer may throw when connecting to the server:

When the socket constructor requests a connection to the server, the following exception may be thrown:

L unknownhostexception: if the host name or IP address cannot be identified, this exception is thrown.

L connectexception: If no server process listens to a specified port or the server process rejects the connection, this exception is thrown.

L sockettimeoutexception: if the connection times out, this exception is thrown.

L bindexception: If the socket object cannot be bound to the specified local IP address or port, this exception is thrown.

2. Obtain socket Information

Use the following method to obtain information about a socket:

L getinetaddress (): Obtain the IP address of the remote server.

L getport (): Obtain the port of the remote server.

L getlocaladdress (): Obtain the local IP address of the customer.

L getlocalport (): Obtain the local port of the customer.

L getinputstream (): gets the input stream. If the socket is not connected, closed, or the input stream is closed using the shutdowninput () method, ioexception is thrown.

L getoutputstream (): gets the output stream. If the socket is not connected, closed, or the output stream is closed using the shutdownoutput () method, ioexception is thrown.

3. Disable socket

1. When the communication between the customer and the server ends, the socket should be closed in time to release various resources, including ports, occupied by the socket. The close () method of the socket is used to close the socket. RecommendationCodeAs follows:

Socket socket =Null;

Try{

Socket =NewSocket ("www.javathinker.org", 80 );

// Receives and sends data.

...

}Catch(Ioexception e ){

E. printstacktrace ();

}Finally{

Try{

If(Socket! =Null) Socket. Close ();

}Catch(Ioexception e) {e. printstacktrace ();}

}

2. the socket class provides three state testing methods:

L isclosed ()

L isconnected ()

L isbound ()

3. To determine whether a socket object is currently connected, use the following methods:

Boolean isconnected = socket. isconnected ()&&! Socket. isclosed ();

Iv. semi-closed socket

1. Sometimes, you may only want to close the output stream or one of the input streams. In this case, you can use the semi-close method provided by the socket class:

L shutdowninput (): closes the input stream.

L shutdownoutput (): Close the output stream.

2. The shutdowninput () and shutdownoutput () Methods of socket are called successively. They only close the input stream and output stream, and are not equivalent to the close () method of socket. After the communication ends, you still need to call the close () method of the socket, because only this method can release the resources occupied by the socket, such as the local port occupied.

3. the socket class also provides two state testing methods to determine whether the input stream and output stream are closed:

L public Boolean isinputshutdown ()

L public Boolean isoutputshutdown ()

5. set socket options

Socket has the following options:

N tcp_nodelay: indicates that data is sent immediately.

N so_resuseaddr: Indicates whether to allow reuse of the local address bound to the socket.

N so_timeout: the timeout value for receiving data.

N so_linger: Indicates whether to immediately close the underlying socket when the close () method of the socket is executed.

N so_snfbuf: the size of the buffer for sending data.

N so_rcvbuf: the buffer size of the received data.

N so_keepalive: Indicates whether to automatically disable a socket that is idle for a long time.

N oobinline: Indicates whether a byte of TCP emergency data can be sent.

1. tcp_nodelay Option

1) set this option: Public void settcpnodelay (Boolean on) throws socketexception

2) read this option: Public Boolean gettcpnodelay () throws socketexception

3) The default value of tcp_nodealy is false, indicating that negale is used.Algorithm. If you call the settcpnodelay (true) method, the socket buffer is disabled to ensure timely data transmission:

If (! Socket. gettcpnodelay () socket. settcpnodelay (true );

4) if the underlying implementation of the socket does not support the tcp_nodelay option, the gettcpnodelay () and settcpnodelay () Methods throw a socketexception.

2. so_resuseaddr Option

1) set this option: Public void setresuseaddress (Boolean on) throws socketexception

2) read this option: Public Boolean getresuseaddress () throws socketexception

3) to ensure that a process closes the socket, even if it has not released the port, other processes on the same host can immediately reuse the port, you can call the setresuseaddress (true) of the socket) method:

If (! Socket. getresuseaddress () socket. setresuseaddress (true );

4) It is worth noting that the socket. setresuseaddress (true) method must be called before the socket is bound to a local port. Otherwise, the socket. setresuseaddress (true) method is invalid. Therefore, you must create a socket object and connect to the remote server as follows:

Socket socket =NewSocket (); // at this time, the socket object is not bound to the local port and is not connected to the remote server

Socket. setresuseaddress (True);

Socketaddress remoteaddr =NewInetsocketaddress ("remotehost", 8000 );

Socket. Connect (remoteaddr);// Connect to the remote server and bind an anonymous local port

Or:

Socket socket =NewSocket (); // at this time, the socket object is not bound to the local port and is not connected to the remote server

Socket. setresuseaddress (True);

Socketaddress localaddr =NewInetsocketaddress ("localhost", 9000 );

Socketaddress remoteaddr =NewInetsocketaddress ("remotehost", 8000 );

Socket. BIND (localaddr); // bind to the local port

Socket. Connect (remoteaddr);// Connect to the remote server and bind an anonymous local port

3. so_timeout Option

1) set this option: Public void setsotimeout (INT milliseconds) throws socketexception

2) read this option: Public int getsotimeout () throws socketexception

3) when reading data through the socket input stream, if there is no data, it will wait. The so_timeout option of the socket class is used to set the wait time-out time for receiving data, in milliseconds. Its default value is 0, indicating unlimited waiting and never timeout.

4) The setsotimeout () method of socket must be executed before receiving data. In addition, when the read () method of the input stream throws sockettimeoutexception, the socket is still connected and you can try to read the data again.

4. so_linger Option

1) set this option: Public void setsolinger (Boolean on, int seconds) throws socketexception

2) read this option: Public int getsolinger () throws socketexception

3) The so_linger option is used to control the behavior when the socket is closed.

L socket. setsolinger (true, 0): When the close () method of the socket is executed, this method will return immediately, but the underlying socket will also be closed immediately, all the remaining data that has not been sent is discarded.

L socket. setsolinger (true, 3600): When the close () method of the socket is executed, this method does not return immediately, but enters the blocking state. At the same time, the underlying socket will try to send the remaining data. The close () method returns only if one of the following conditions is met:

N the underlying socket has sent all the remaining data.

N although the underlying socket has not sent all the remaining data, it has blocked 3600 seconds. If the blocking time of the close () method exceeds 3600 seconds, it will return, and the remaining unsent data will be discarded.

In the preceding two cases, when the close () method returns, the underlying socket is closed and the connection is closed.

4) In the setsolinger (Boolean on, int second) method, the seconds parameter is measured in seconds rather than milliseconds.

5. so_rcvbuf Option

1) set this option: Public void setreceivebuffersize (INT size) throws socketexception

2) read this option: Public int getreceivebuffersize () throws socketexception

3) so_rcvbuf indicates the buffer size of the socket for input data.

4) if the underlying socket does not support the so_rcvbuf option, the setreceivebuffersize () method will throw a socketexception.

6. so_sndbuf Option

1) set this option: Public void setsendbuffersize (INT size) throws socketexception

2) read this option: Public int getsendbuffersize () throws socketexception

3) so_sndbuf indicates the buffer size of the socket used to output data.

4) if the underlying socket does not support the so_sndbuf option, the setsendbuffersize () method will throw a socketexception.

7. so_keepalive Option

1) set this option: Public void setkeepalive (Boolean on) throws socketexception

2) read this option: Public int getkeepalive () throws socketexception

3) when the so_keepalive option is true, the underlying TCP implementation will monitor whether the connection is valid.

4) The default value of the so_keepalive option is false, indicating that TCP does not monitor whether the connection is valid. The idle client may exist permanently without notice that the server has crashed.

8. oobinline options

1) set this option: Public void setoobinline (INT size) throws socketexception

2) read this option: Public int getoobinline () throws socketexception

3) When oobinline is true, it indicates that one byte of TCP emergency data can be sent. The sendurgentdate (INT data) method of the socket class is used to send a byte of TCP emergency data.

4) The default value of oobinline is false. In this case, when the recipient receives the URGent data, it will not be processed and discarded directly. If you want to send emergency data, set oobinline to true: Socket. setoobinline (true). At this time, the receiver places the received emergency data in the same queue as the normal data. It is worth noting that, unless some higher-level protocols are used, the recipient's ability to process urgent data is very limited. When URGent data arrives, the recipient will not receive any notification, therefore, it is difficult for the receiver to distinguish between common and urgent data, so they have to be processed in the same way.

9. service type options

1) IP addresses define four service types to describe service quality in a qualitative manner:

L low cost: Low sending cost.

L High Reliability: ensures reliable data delivery to the destination.

L maximum throughput: a large volume of data can be received or sent at a time.

L minimum latency: the data transmission speed is fast, and the data is delivered to the destination quickly.

2) These four service types can also be combined. For example, high reliability and minimum latency can be required at the same time. The socket class provides methods to set and read the service type:

L set the service type: Public void settrafficclass (INT trafficclass) throws socketexception

L read service type: Public int gettrafficclass () throws socketexception

3) The socket class uses four Integers to indicate the service type:

L low cost: 0x02 (the penultimate binary is 1)

L High Reliability: 0x04 (the last and third bits of binary are 1)

L maximum throughput: 0x08 (the last and fourth bits of binary are 1)

L minimum latency: 0x10 (the last and fifth digits of the binary are 1)

10. Set the relative importance of connection time, latency, and bandwidth

Public void setexcepcepreferences (INT connectiontime, int latency, int bandwidth)

The three parameters of the preceding method indicate the three indicators for data transmission over the network:

N parameter connectiontime: specifies the minimum time to establish a connection.

N parameter latency: Minimum latency.

The N parameter bandwidth indicates the maximum bandwidth.

The setexcepcepreferences () method is used to set the relative importance between the three indicators. You can assign any integer to these parameters. The relative size between these integers determines the relative importance of these parameters. For example, if the connectiontime parameter is 2, the latency parameter is 1, and the bandwidth parameter is 3, the maximum bandwidth is the most important, followed by the minimum connection time, and finally the minimum latency.

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.