Java ServerSocket Usage Detailed

Source: Internet
Author: User

In client/server communication mode, the server side needs to create a serversocket,serversocket that listens on a specific port to receive client connection requests.

first, the construction serversocket

The ServerSocket method has the following overloaded forms:

ServerSocket () throws IOException
ServerSocket (int port) throws IOException
ServerSocket (int port, int backlog) throws IOException
ServerSocket (int port, int backlog, inetaddress bindaddr) throws IOException

In the above construction method, the parameter port specifies the port to be bound by the server (the port to be monitored by the server), the parameter backlog specifies the length of the Client connection request queue, and the parameter bindaddr specifies the IP address to bind the server to.

Note: 1. If the port is occupied or does not have permission to use certain ports, it throws a bindexception error. For example, 1~1023 ports require an administrator to have permission bindings. 2. If you set the port to 0, the system will automatically assign it a port, 3. BINDADDR is used to bind the server IP, why there are such settings, such as some machines have multiple network cards. 4. ServerSocket Once the listening port is bound, it cannot be changed. ServerSocket () can be used to set other parameters before the binding end.
TwoBinding Port

In addition to the first construction method without parameters, other construction methods will bind the server to a specific port, which is specified by the parameter port.

For example, the following code creates a server that is bound to port 80:

1 New ServerSocket (80);

If the runtime cannot bind to port 80, the above code throws IOException, or more precisely, throws Bindexception, which is a subclass of IOException.

Bindexception is generally caused by the following reasons:

1. The port has been occupied by other server processes;
2. In some operating systems, if the server program is not running as Superuser, the operating system does not allow the server to bind to a port between 1~1023.

If the parameter port is set to 0, the operating system is assigned an arbitrarily available port for the server. The ports that are assigned by the operating system are also known as anonymous ports. For most servers, an explicit port is used instead of an anonymous port because the client needs to know the port of the server in advance for easy access to the server.

third, set the length of the customer connection request queue

When a server process is running, it is possible to listen to connection requests to multiple customers at the same time.

For example, each time a client process executes the following code:

1 New Socket ("127.0.0.1", 80);

The task for managing client connection requests is done by the operating system. The operating system stores these connection requests in a FIFO queue. Many operating systems limit the maximum length of a queue, typically 50. When a connection request in the queue reaches the maximum capacity of the queue, the host on which the server process resides rejects the new connection request. The queue can continue to join a new connection request only if the server process takes the connection request out of the queue through the ServerSocket accept () method, leaving the queue empty.

For a client process, if the connection request it makes is joined to the server's queue, it means that the client's connection to the server is successful and the client process returns gracefully from the socket construction method. If the connection request made by the client process is rejected by the server, the socket construction method throws connectionexception.

The backlog parameter of the ServerSocket construction method is used to explicitly set the length of the connection request queue, which overrides the maximum length of the operating system-qualified queue. It is worth noting that the maximum length of the operating system-qualified queue is still used in the following cases:

The value of the 1.backlog parameter is greater than the maximum length of the operating system-qualified queue;
The value of the 2.backlog parameter is less than or equal to 0;
3. The backlog parameter is not set in the ServerSocket constructor method.

Fourset the IP address of the binding

If the host has only one IP address, the server program is bound to that IP address by default. ServerSocket's 4th construction method ServerSocket (int port, int backlog, inetaddress bindaddr) has a bindaddr parameter that explicitly specifies the IP address to bind the server to. This construction method applies to hosts that have multiple IP addresses. Assume that a host has two network cards, a network adapter for connecting to the Internet, and an IP address of 222.67.5.94, there is also a network card to connect to the local LAN, the IP address is 192.168.3.4. If the server is only accessed by customers on the local area network, you can create ServerSocket as follows:

ServerSocket serversocket=New ServerSocket (8000,10,inetaddress.getbyname ("192.168.3.4"));
Fivereceive and close a connection to a customer

The Accept () method of ServerSocket pulls a client's connection request from the connection request queue and then creates a socket object that is connected to the client and returns it. If there is no connection request in the queue, the Accept () method waits until a connection request is received to return.

Next, the server obtains the input stream and the output stream from the socket object, and it can exchange data with the customer. When the server is in the operation of sending data, if the client disconnects, then the server side throws a IOException subclass SocketException exception.

SixClose ServerSocket

The close () method of the ServerSocket causes the server to free up the occupied ports and disconnects from all customers. When a server program finishes running, the operating system frees the port that the server occupies, even if the close () method of ServerSocket is not executed. Therefore, the server program does not necessarily have to execute the close () method of ServerSocket before the end.

The isClosed () method of the ServerSocket determines whether the ServerSocket is closed, only the close () method of ServerSocket is executed, and the IsClosed () method returns true; The isClosed () method returns false even if ServerSocket has not yet been bound to a specific port.

The ServerSocket Isbound () method determines whether ServerSocket is already bound to a port, as long as ServerSocket is already bound to a port, and even if it has been closed, the Isbound () method returns True.

If you need to determine that a serversocket has been bound to a specific port and has not been closed, you can do this in the following ways:

1 boolean isOpen = Serversocket.isbound () &&!serversocket.isclosed ();
Sevenget information on ServerSocket

The following two get methods of ServerSocket can obtain the IP address of the server binding separately, and the bound port:

Public inetaddress getinetaddress ()//Get Service IP Address
public int Getlocalport ()//Get server-bound port

Eightserversocket Options

ServerSocket has the following 3 options.

So_timeout: Represents the time-out period waiting for a client connection.
SO_REUSEADDR: Indicates whether to allow reuse of addresses that are bound by the server.
SO_RCVBUF: Represents the size of the buffer that receives the data.

Please refer to the courseware for specific usage, thank you!

Source:

Http://www.cnblogs.com/rond/p/3565113.html

Http://www.51cto.com/specbook/11/40196.htm

Java ServerSocket 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.