Chapter II the socket usage detailed

Source: Internet
Author: User

2.1 Constructing sockets

The socket construction method is as follows:

1 Socket ()2 //creates an unconnected socket with the System-default type of SocketImpl.3  4Socket (inetaddress address,intPort)5 //creates a stream socket and connects it to the specified port number at the6 //specified IP address.7  8Socket (inetaddress host,intPortBooleanstream)9 //Deprecated. Ten //Use the datagramsocket instead for UDP transport. One   ASocket (inetaddress address,intPort, InetAddress localaddr,intLocalPort) - //creates a socket and connects it to the specified remote address on the - //specified remote port. the   - Socket (proxy) - //creates an unconnected socket, specifying the type of proxy, if any, that - //should is used regardless of any other settings. +   - Socket (SocketImpl impl) + //creates a unconnected Socket with a user-specified socketimpl. A   atSocket (String host,intPort) - //creates a stream socket and connects it to the specified port number on the - named host. -   -Socket (String host,intPortBooleanstream) - //Deprecated.  in //Use the datagramsocket instead for UDP transport. -   toSocket (String host,intPort, InetAddress localaddr,intLocalPort) + //creates a socket and connects it to the specified remote host on the specified - //remote port.

In addition to the first none, the rest of the constructor attempts to establish a connection to the server, and if successful, returns the socket object, no exception is thrown.

Based on the above construction method, a class is created to scan whether the port between 1-1024 on the host is being monitored by the server program (and if it is listening, it can return the socket object). The code is as follows:

Importjava.io.IOException;ImportJava.net.Socket; Public classPortscanner { Public Static voidMain (string[] args) {String host= "localhost"; NewPortscanner (). Scan (host); }     Public voidScan (String host) {Socket socket=NULL;  for(intport=1;port<=1024;port++){            Try{Socket=NewSocket (Host,port); System.out.println ("There is a server on port" +port); }Catch(IOException e) {System.out.println ("Can ' t connect to port" +port); }finally{                if(socket!=NULL){                    Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); }                }            }        }    }}

  

  2.1.1 Setting the timeout to wait for the connection to be established

When you need to set the connection timeout time, you need to call the socket's parameterless constructor.

    

New Socket (); // SocketAddress provides immutable objects for sockets to bind, concatenate, or use as return values.  New inetsocketaddress ("localhost", 8000); // A timeout exception is thrown when the timeout is not connected. Socket.connect (remoteaddr,60000); // milliseconds, 0 for no time-out

  2.1.2 Setting the server address

In addition to the first parameterless constructor, the rest needs to provide the server IP or host name, and the port number.

    

1 socket (inetaddress address,int port)  // The first parameter indicates the host IP address 2 socket ( String host,int port)  // first indicates host name
View Code

The InetAddress class represents the IP address of the server, see here for details.

  2.1.3 Setting the client address

A socket object should contain the IP and port information of the remote server, as well as the IP address and port information of the local client. By default, the IP of the client is from the local host and the port has an operating system assigned automatically. You can also explicitly set the IP and port of the client.

   

Socket (inetaddress address,int port,inetaddress localaddress,int  localport) socket ( String host,int port,int port,inetaddress localaddress,int localport)

 2.1.4 Possible exceptions for client connection servers

   

unknownhostexception
Span style= "FONT-SIZE:16PX;" >connectexception
Span style= "FONT-SIZE:16PX;" >sockettimeoutexception wait for connection timeout
bindexception

2.2 Getting socket information

  The following methods are available for socket related information:

1 inetaddress getinetaddress ()2 //Returns the address to which the socket is connected.3  4 InputStream getInputStream ()5 //Returns An input stream for this socket.6 7 outputstream Getoutputstream ()8 //Returns An output stream for this socket.9  Ten intGetport () One //Returns The remote port number to which this socket is connected. A   - inetaddress getlocaladdress () - //Gets The local address to which the socket is bound. the   - intGetlocalport () - //Returns The local port number to which this socket is bound.

2.3 Closing the socket

  Some of the code is as follows:

if (socket!=null) {    try  {        socket.close ();     Catch (IOException e) {        e.printstacktrace ();        }    }
}

The socket provides 3 status test methods:

Boolean//Returns The binding state of thesocket. Boolean  //Returns The closed state of thesocket. Boolean isconnected ()   // Returns the connection state of the socket.

2.4 Half-closed socket

  When process a communicates with process B, a transmits data to B, how do you tell B that all the data has been transferred? Here are a few ways:

(1) Send a special line of strings, such as the "Bye" used in the previous chapter, to inform the output is complete.

(2) A first tells the length of the string B and transmits the data to B.

(3) A When the send is complete, close the socket. At this point, after reading the data, when read () is executed, the method returns-1 and returns null if the BufferedReader ReadLine () method is executed. This means that the end of the input stream is reached.

(4) Close the input and output stream of the socket

Shutdowninput (): Close input stream

Shutdownoutput (): Turn off the output stream

Corresponds to two state test methods:

Isinputshutdown ()

Isoutputshutdown ()

Chapter II the 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.