Network communication Scoket in Java

Source: Internet
Author: User
Tags stringbuffer

In client/server communication mode, the client needs to proactively establish a socket connected to the server, the server receives a connection request from the client, and a socket connected to the client is created. A socket can be seen as a transceiver on both ends of a communication connection, and both the client and the service store send and receive data via sockets.

1. Structure socket

Public socket () creates an SOCKETIMPL socket from the system default type

Public Socket (String host,int port) throws unknownhostexception,ioexception creates a stream socket and connects it to the specified port number on the specified host.

The public socket (String host,int port,inetaddress localaddr,int localport) throws IOException creates a socket and connects it to the specified remote port on the specified remote host. The socket binds the provided local address and port by calling the bind () function.

The public Socket (inetaddress address,int port) throws IOException creates a stream socket and connects it to the specified port number for the specified IP address.

Public Socket (inetaddress address,int port,inetaddress localaddr,int localport) throws IOException creates a socket and connects it to the specified remote port on the specified remote address. The socket binds the provided local address and port by calling the bind () function.

In addition to the first, the other 4 construction methods attempt to establish a connection to the server, and if the connection succeeds, the socket object is returned, and IOException is thrown if the connection fails.

Example 1: Scan 1 to 1024 ports on the host to determine if the ports are being monitored by the server

Package Com.hanfeng.socket;import java.io.ioexception;import java.net.socket;/** * Scan 1 to 1024 ports on the host to determine if these ports are being monitored by the server *  * @author Hanfeng * @data 2012-8-24 a.m. 10:25:57 */public class Portscanner {public static void main (string[] args) {St Ring host = "localhost"; if (Args.length > 0) {host = Args[0];} New Portscanner (). Scan (host);} public void Scan (String host) {Socket socket = null;for (int port = 1; port < 1024x768; port++) {try {socket = new socket (h OST, Port); SYSTEM.OUT.PRINTLN ("Connect to Port:" + port);} catch (IOException e) {System.out.println ("Cannot connect to port:" + port);} finally {try {if (socket! = NULL) {Socket.close ()}} catch (Exception e) {E.printstacktrace ();}}}}}

1.1 Setting the Wait connection time-out period

public void Scan (String host) {socket socket = Null;socket = new socket (); SocketAddress address = new Inetsocketaddress (host, 1158); try {socket.connect (address, 60000); SYSTEM.OUT.PRINTLN ("Connection Successful! ");} catch (IOException e) {System.out.println ("Connection timed out! "); E.printstacktrace ();}}

1.2 Set the IP address of the server

Socket (inetaddress address, int port)//First parameter address indicates the IP address of the host
Socket (String host, int port)//The first parameter, host, indicates the name of the hostname

The InetAddress class represents an IP address and uses the following:
Returns the IP address of the local host
InetAddress Addr1=inetaddress.getlocalhost ();
Returns the IP address that represents "222.34.5.7"
InetAddress addr2=inetaddress.getbyname ("222.34.5.7");
Returns the IP address of the domain name "www.google.com"
InetAddress addr3=inetaddress.getbyname ("www.google.com");

public static void Main (string[] args) {try {inetaddress address = inetaddress.getlocalhost (); System.out.println ("Native IP address:" +address); inetaddress address2 = Inetaddress.getbyname ("222.34.5.7"); SYSTEM.OUT.PRINTLN ("Return Remote IP Address:" +address2); inetaddress address3 = Inetaddress.getbyname ("www.google.com"); SYSTEM.OUT.PRINTLN ("Return domain name IP address:" +ADDRESS3);} catch (Unknownhostexception e) {e.printstacktrace ();}}

1.3 Setting the IP address of the client

In a socket object, it contains both the IP address and port information of the remote server, as well as the IP address and port information of the local client. By default, the IP address of the client is from the host where the client is located, and the port is randomly assigned by the operating system. The socket class also has two construction methods that allow the client's IP address and port to be set explicitly:
Socket (inetaddress address, int port, inetaddress localaddr, int localport) throws IOException
Socket (String host, int port, inetaddress localaddr, int localport) throws IOException

Example: The IP address of a host in an Internet network is "222.67.1.34" and the IP address in a LAN is "112.5.4.3". Assuming the client program on this host wants to communicate with a server program (112.5.4.45:8000) on the same LAN, the client can construct the socket object as follows:

InetAddress remoteaddr = Inetaddress.getbyname ("112.5.4.45"); InetAddress localaddr = Inetaddress.getbyname (" 112.5.4.3 "); Socket socket = new socket (remoteaddr,8000,localaddr,2345);

1.4 Exceptions that may be thrown by client connection servers

Unknowhostexception: If the host's name or IP address is not recognized, an exception is thrown

Connectexception: If there is no server listening on the specified port or the server process rejects the connection, an exception will be thrown

Sockettimeoutexception: Waiting for connection timeout, throwing exception

Bindexcrption: If the socket object cannot be bound to a specific local IP address or port, an exception will be thrown

The above 4 exceptions are ioexception direct or indirect subclasses, such as

Example: Capturing various exceptions

Package Com.hanfeng.socket;import Java.io.ioexception;import Java.net.bindexception;import Java.net.connectexception;import Java.net.inetsocketaddress;import Java.net.socket;import java.net.SocketAddress; Import Java.net.sockettimeoutexception;import java.net.unknownhostexception;/** * * @author Hanfeng * @data 2012-8-24 morning 11:16:32 */public class Connecttest {public static void main (string[] args) {String host = "www.google.com"; int port = 80; if (args.length>1) {host = Args[0];p ort = Integer.parseint (args[1]);} New Connecttest (). Connect (host, port);} public void Connect (String host,int port) {socketaddress address = new Inetsocketaddress (host, Port); Socket socket = NULL; String result = ""; try {long begin = System.currenttimemillis ();//Compute the time to start the connection socket = new socket ();//Start Establishing Connection Socket.connect ( address, 6000);//Set connection timeout time long end = System.currenttimemillis ();//end of computer connection time result = (End-begin) + "MS";} catch (Bindexception e) {result = "IP address or port binding exception! ";} catch (Unknownhostexception e) {result = "The Master is not recognizedMachine Address! ";} catch (Sockettimeoutexception e) {result = "Connection timed out! ";} catch (Connectexception e) {result = "Deny connection! ";} catch (Exception e) {result = "Failed! ";} Finally{if (socket!=null) {try {socket.close ();} catch (IOException e) {e.printstacktrace ();}}} SYSTEM.OUT.PRINTLN ("Remote Address information ==>" +address+ ":" +result);}}

2. Get socket Information

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. This method throws IOException if the socket has not yet been connected, or has been closed, or the input stream has been closed through the Shutdowninput () method.
Getoutputstream (): Gets the output stream. This method throws IOException if the socket has not yet been connected, or has been closed, or the output stream has been closed through the Shutdownoutput () method.

Example: HttpClient class Access Web page

Package Com.hanfeng.socket;import Java.io.bufferedreader;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.net.Socket;public Class Httpclientdemo {String host = "www.google.com"; int port = 80; Socket socket = Null;public void Createsocket () throws Exception{socket = new socket (host, port);} public void Communicate () throws exception{StringBuffer sb=new stringbuffer ("GET" + "http/1.1\r\n");//Sb.append ("H Ost:www.javathinker.org\r\n ");//Sb.append (" Accept: */*\r\n ");//Sb.append (" accept-language:zh-cn\r\n ");//SB.A Ppend ("Accept-encoding:gzip, deflate\r\n");//Sb.append ("user-agent:mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0) \ r \ n ");//Sb.append (" connection:keep-alive\r\n\r\n ");//Send HTTP request OutputStream Socketout = Socket.getoutputstream (); Socketout.write (Sb.tostring (). GetBytes ()); Socket.shutdownoutput ();//Receive Response results InputStream Socketinput = Socket.getinputstream (); BufferedReader bUffer = new BufferedReader (new InputStreamReader (Socketinput)); String data = Null;while ((Data=buffer.readline ())!=null) {System.out.println (data);}} /** * @param args * @throws Exception */public static void Main (string[] args) throws Exception {Httpclientdemo Httpclien t = new Httpclientdemo (); Httpclient.createsocket (); Httpclient.communicate ();}}

3. Close 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, I/O operations cannot be performed through his input stream and output stream, otherwise it will cause ioexception.

To ensure that the operation to close the socket is always executed, it is recommended that this operation be placed in the finally code block.

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

IsConnected (): Returns True if the socket was connected to a remote host

Isbound (): Returns True if the socket is already bound to a local port

If you want to determine whether a socket object is currently connected, you can use the following method:

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

4, half closed socket

4.1 Sometimes you might just want to close one of the output streams or the input stream. You can now use the semi-closing method provided by the socket class:

Shutdowninput (): closes the input stream.

Shutdownoutput (): Turns off the output stream.

4.2 Calling the Shutdowninput () and Shutdownoutput () methods of the socket, simply shutting down the input and output streams, is not equivalent to calling the close () method of the socket. After the communication is over, the close () method of the socket is still called, because only the method frees the resource that the socket occupies, such as the local port occupied.

The 4.3 socket class also provides two state test methods to determine if the input and output streams are closed:

public boolean Isinputshutdown ()

public boolean Isoutputshutdown ()

5, set the socket options

The socket has several options:

N tcp_nodelay: Indicates that data is sent immediately.

N so_resuseaddr: Indicates whether the local address to which the socket is bound is allowed to be reused.

N so_timeout: Indicates the wait time-out period when data is received.

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

N so_snfbuf: Indicates the size of the buffer that sent the data.

N So_rcvbuf: Represents the size of the buffer that receives the data.

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

N oobinline: Indicates whether to support sending a byte of TCP emergency data.

1. Tcp_nodelay Options

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, which means that the Negale algorithm is used. If the Settcpnodelay (True) method is called, the buffer of the socket is closed, ensuring that the data is sent in a timely manner:

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

4) If the underlying implementation of the socket does not support the Tcp_nodelay option, then the Gettcpnodelay () and Settcpnodelay () methods will throw socketexception.

2. SO_RESUSEADDR Options

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 shuts down the socket, even if it does not release the port, other processes on the same host can immediately reuse the port, you can call the socket's Setresuseaddress (true) method:

if (!socket.getresuseaddress ()) socket.setresuseaddress (true);

4) It is important to note that the Socket.setresuseaddress (true) method must be called before the socket is bound to a local port, otherwise the execution of the Socket.setresuseaddress (true) method is not valid. Therefore, you must create the socket object in the following manner before connecting to the remote server:

Socket socket = new socket (); The socket object is not bound to a local port at this time and the remote server is not connected

Socket.setresuseaddress (true);

SocketAddress remoteaddr = new inetsocketaddress ("RemoteHost", 8000);

Socket.connect (REMOTEADDR); Connect to the remote server and bind the anonymous local port

Or:

Socket socket = new socket (); The socket object is not bound to a local port at this time and the remote server is not connected

Socket.setresuseaddress (true);

SocketAddress localaddr = new inetsocketaddress ("localhost", 9000);

SocketAddress remoteaddr = new inetsocketaddress ("RemoteHost", 8000);

Socket.bind (LOCALADDR); Bind to Local port

Socket.connect (REMOTEADDR); Connect to the remote server and bind the anonymous local port

3. So_timeout Options

1) Set this option: public void setsotimeout (int milliseconds) throws SocketException

2) Read this option: public int getsotimeout () throws SocketException

3) When the data is read through the input stream of the socket, it waits if there is no data. The so_timeout option of the socket class is used to set the wait timeout for received data in milliseconds, with a default value of 0, which means that it waits indefinitely and never times out.

4) The Setsotimeout () method of the socket must be executed before the data is received. Also, 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 Options

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 of the socket when it is closed.

L Socket.setsolinger (true,0): When the Close () method of the socket is executed, the method returns immediately, but the underlying socket is immediately closed, and any remaining data that is not sent is discarded.

L Socket.setsolinger (true,3600): When the Close () method of the socket is executed, the method does not return immediately and enters the blocking state, while the underlying socket attempts to send the remaining data. The close () method returns only if one of the following two conditions is true:

n the bottom socket has sent out all the remaining data.

n Although the underlying socket has not yet sent out all of the remaining data, it has been blocked for 3,600 seconds. The close () method has a blocking time of more than 3,600 seconds and is also returned, leaving the remaining unsent data discarded.

In both cases, when the close () method returns, the underlying socket is closed and disconnected.

4) The seconds parameter in the Setsolinger (Boolean on, int second) method is in seconds, not in milliseconds.

5. SO_RCVBUF Options

1) Set this option: public void setreceivebuffersize (int size) throws SocketException

2) Read this option: public int getreceivebuffersize () throws SocketException

3) So_rcvbuf represents the size of the socket's buffer for input data.

4) If the underlying socket does not support the SO_RCVBUF option, then the Setreceivebuffersize () method throws SocketException.

6. SO_SNDBUF Options

1) Set this option: public void setsendbuffersize (int size) throws SocketException

2) Read this option: public int getsendbuffersize () throws SocketException

3) So_sndbuf represents the size of the socket's buffer for output data.

4) If the underlying socket does not support the SO_SNDBUF option, the Setsendbuffersize () method throws SocketException.

7. So_keepalive Options

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 that the connection is valid.

4) The default value of the So_keepalive option is false, which means that TCP does not monitor whether the connection is valid, and inactive clients may persist indefinitely without noticing 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, the TCP emergency data that sends a byte is supported. 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 which case the receiving party does not make any processing when it receives the emergency data and discards it directly. If the user wants to send emergency data, the Oobinline should be set to True:socket.setOOBInline (true); At this point the receiver puts the received emergency data in the same queue as the normal data. It is important to note that unless a higher level protocol is used, the receiver's ability to process emergency data is very limited, and when emergency data arrives, the receiver will not be notified, so it is difficult for the receiver to differentiate between ordinary and emergency data and have to deal with them in the same way.

Network communication Scoket in Java

Related Article

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.