Transmission Control Protocol for Java Network Programming (II)

Source: Internet
Author: User

Iv. Socket

The Socket class represents a client Socket, which is a communication channel between two TCP communication ports of one or two computers. The port can be connected to another port of the local system, which can avoid using another computer, but most network software will use two computers.
However, TCP sockets cannot communicate with more than two computers. If this function is required, the client application must establish multiple socket connections with one socket for each computer.

Constructor

The java.net. Socket class has several constructors. The two constructors allow the use of Boolean parameters to specify whether UDP or TCP sockets are used. We do not agree to use them. These two constructors are not used here and are not listed here -- use DatagramSocket if UDP is required. Iv. Socket

The Socket class represents a client Socket, which is a communication channel between two TCP communication ports of one or two computers. The port can be connected to another port of the local system, which can avoid using another computer, but most network software will use two computers.
However, TCP sockets cannot communicate with more than two computers. If this function is required, the client application must establish multiple socket connections with one socket for each computer.

Constructor

The java.net. Socket class has several constructors. The two constructors allow the use of Boolean parameters to specify whether UDP or TCP sockets are used. We do not agree to use them. These two constructors are not used here and are not listed here -- use DatagramSocket if UDP is required.

Try
{
// Connect to the specified host and Port
Socket mySocket = new Socket ("www.awl.com", 80 );

//......
}
Catch (Exception e)
{
System. err. println ("Err-" + e );
}

However, many constructors can be used in different situations. Unless otherwise specified, all constructors are public.

· Protected Socket ()-use the current Socket to generate the default Socket provided by the component to establish a non-connection Socket. Generally, developers should not use this method because it does not allow specifying host names and ports.

· Socket (InetAddress address, int port) generates java. io. IOException.

· Java. lang. SecurityException-Establish a socket to connect to the specified IP address and port. This exception occurs if a connection cannot be established or the host violates security constraints, for example, when a small service program attempts to connect to a computer instead of loading it to the computer.

· Socket (InetAddress address, int port, InetAddress localAddress, int localPort) generates java. io. IOException, java. lang. securityException exception-creates a socket to connect to the specified address and port, and binds it to a specific local address and local port. By default, a free and empty port is used, but in a multi-address host environment, for example, a local host has two or more computers, this method also allows you to specify a specific port number and address.

· Protected Socket (SocketImpl implementation) -- use a specific Socket to implement implementation) to create an unconnected Socket. Generally, developers should not use this method because it allows you to specify the host name and port.

· Socket (String host, int port) generates java.net. UnknownHostException, java. io. IOException, java. lang. SecurityException exception -- creates a Socket to connect to a specific host and port. This method allows you to specify a string instead of an InetAddress. If the specified host name cannot be resolved, the connection cannot be established. If the security constraints are violated, an exception occurs.

· Socket (String host, int port, InetAddress localAddress, int localPort) generates java.net. unknownHostException, java. io. IOException, java. lang. securityException exception-creates a socket to connect to a specific host and port and binds it to a specific local port and address. It allows you to specify a host name in the string format, instead of an InetAddress instance. It also allows you to specify a local address and port to be bound. These local parameters are useful for computers with multiple IP addresses that can be accessed through two or more IP addresses. If the host name cannot be resolved, a connection cannot be established. If the host name violates the security constraints, an exception occurs.

1. Create a socket

In a normal environment, when a socket is established, it connects to a computer and a port. Although there is an empty constructor that does not require a host name or port, but it is a protected), it cannot be called in normal applications. In addition, there is no connect () method used to specify the detailed information in the future, so the connection should be established in a normal environment. If the network is good, the call to the socket constructor will return immediately when the connection is established. However, if the remote computer does not respond, the constructor method may be blocked for a period of time. This varies with the system. It depends on multiple factors, for example, the operating system in use and the default network timeout settings, for example, some computers in the local LAN usually respond faster than computers on the Internet ). You cannot even be sure how long the socket will be blocked, but this is abnormal and it will not appear frequently. Even so, it may be more appropriate to place such calls in the second thread in the key transaction system to prevent the application from stopping.

Note:

At a lower level, a socket is generated by a socket factory component. It is a special class responsible for establishing an appropriate socket implementation. In normal environments, the standard java.net. socket, but in some special circumstances, such as using a special network environment of a custom Socket, such as using a special proxy server to penetrate the firewall ), the socket generation component may actually return a socket subclass ). Familiar with the intricate Java Network programming, it is clear that experienced developers who want to build custom sockets and socket generation components can learn the details of socket generation components. For more information about this topic, see the Java API documentation for the java.net. SocketFactory and java.net. SocketImplFactory classes.

2. Use SOCKET

A socket can execute a large number of transactions, such as reading information, sending data, closing connections, and setting SOCKET options. In addition, the following method can be used to obtain socket information, such as the address and port location ):

Method

· Void close () generates java. io. IOException -- closes the socket connection. Disabling the connection may or may not allow sending the remaining data, depending on the SO_LINGER socket options. We recommend that you clear all output streams before closing the socket connection.

· InetAddress getInetAddress () -- return the address of the remote host connected to the socket.

· InputStream getInputStream () generates a java. io. IOException exception -- an input stream is returned, which reads information from the application connected to the socket.

· OutputStream getOutputStream () generates a java. io. IOException exception -- an output stream is returned, which writes information to the application connected to the socket.

· Boolean getKeepAlive () generates a java.net. SocketException exception -- the status of the SO_KEEPALIVE socket option is returned.

· InetAddress getLocalAddress () -- returns the local address associated with the socket, which is useful in Multi-address computers ).

· Int getLocalPort () -- return the port number bound to the socket on the local computer.

· Int getPort () -- return the port number of the remote service that the socket is connected.

· Int getReceiveBufferSize () generates a java.net. SocketException exception -- returns the size of the receiving buffer used by the socket, which is determined by the value of the SO_RCVBUF socket option.

· Int getSendBufferSize () generates a java.net. SocketException exception -- return the size of the sending buffer used by the socket, which is determined by the value of the SO_SNDBUF socket option.

· Int getSoLinger () generates a java.net. SocketException exception -- returns the value of the SO_LINGER socket option, which controls how long the unsent data will be queued when the connection is terminated.

· Int getSoTimeout () generates a java.net. SocketException exception -- returns the value of the SO_TIMEOUT socket option, which controls how many milliseconds the read operation will block. If the returned value is 0, the timer is disabled and the thread is blocked indefinitely until the data can be used or the stream is terminated ).

· Boolean getTcpNoDelay () generates a java.net. SocketException exception -- if the setting of the TCP_NODELAY socket option is enabled, "true" is returned, which controls whether the Nagle algorithm is allowed.

· Void setKeepAlive (boolean onFlag) generates a java.net. SocketException exception -- allow or disable the SO_KEEPALIVE socket option.

· Void setReceiveBufferSize (int size) generates java.net. SocketException exception -- modifies the value of the SO_RCVBUF socket option, which is the buffer size recommended for receiving input data for the network code of the operating system. Not every system supports this function or allows absolute control of this feature. If you want to buffer the input data, we recommend that you use BufferedInputStream or BufferedReader.

· Void setSendBufferSize (int size) generates a java.net. SocketException exception -- modifies the value of the SO_SNDBUF socket option, which is the buffer size recommended for sending input data for the network code of the operating system. Not every system supports this function or allows absolute control of this feature. If you want to buffer the input data, we recommend that you use BufferedOutputStream or Buffered Writer.

· Static void setSocketImplFactory (SocketImplFactory factory) to generate java.net. socketException, java. io. IOException, java. lang. securityException exception-specifies a socket implementation component for the JVM, which can already exist or violate security constraints. Exceptions may occur in either case. Only one production component can be specified. This component is used when a socket is created.

· Void setSoLinger (boolean onFlag, int duration) generates java.net. socketException, java. lang. illegalArgumentException exception -- enable or disable the SO_LINGER socket option based on the value of the Boolean parameter onFlag), and specify the duration calculated in seconds. If a negative value is specified, an exception occurs.

· Void setSoTimeout (int duration) generates a java.net. SocketException exception -- modifies the value of the SO_TIMEOUT socket option, which controls how long the read operation will be blocked in milliseconds ). If the value is 0, the timeout setting is disabled, causing an indefinite blocking. If a timeout occurs, a java. io. IOInterruptedException exception occurs when a read operation occurs on the input stream of the socket. This is completely different from the internal TCP timer, which triggers the re-sending process of unknown packets.

· Void setTcpNoDelay (boolean onFlag) generates a java.net. SocketException exception -- activates or disables the TCP_NODELAY socket option and determines whether to use the Nagle algorithm.

· Void shutdownInput () generates a java. io. IOException exception -- closes the input stream associated with the socket and deletes all more information sent. Further reading of the input stream will experience the end identifier of the stream.

Related Articles]

  • Use Ethereal to learn TCP/IP protocol
  • Use TCP/IP protocol to implement chat program
  • TELNET TCP/IP terminal simulation Protocol

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.