Java Network Programming II: Socket detailed

Source: Internet
Author: User

Socket, also known as socket, is the endpoint that connects two-way communication between two programs on the network.

The process of using a socket for network communication

Service side: The server program binds a socket to a specific port and waits and listens to the client's connection request through this socket.

Client: The client program makes a connection request based on the host name and port number where your server resides.

The communication between the two is done through the socket, we can think that the socket is a transport between the two cities, with it, you can travel between the two cities.

Socket Communication Example

Host A's application communicates with Host B's application and must establish a connection through the socket, and a socket must be established by the underlying TCP/IP protocol to establish a TCP connection. Establishing a TCP connection requires the underlying IP protocol to address the hosts in the network. The IP address can only help us find the target host, but a host with multiple applications, how to find the application we need, this time can be specified by the port number.

Second, the simple service side, the client simulation

Server-side:

1      Public Static voidMain (string[] args)throwsIOException2     {3         //Create a ServerSocket that listens for client socket connection requests4ServerSocket SS =NewServerSocket (8888);5SYSTEM.OUT.PRINTLN ("Server Start");6         //listens for client requests in a circular manner7          while(true)8         {9             //listens for and accepts connections to this socket. This method is blocked until the connection is passed in. TenSocket socket =ss.accept (); OneOutputStream OS =Socket.getoutputstream (); APrintStream PS =Newprintstream (OS); -Ps.print ("Hello, you received a blessing from the service side of the Mid-Autumn Festival"); - ps.close (); the os.close (); - socket.close (); -         } -}

Execution Result:

Server start

Client:

1      Public Static voidMain (string[] args)throwsIOException, Exception2     {3Socket socket =NewSocket ("localhost", 8888);4InputStream is =Socket.getinputstream ();5BufferedReader br =NewBufferedReader (NewInputStreamReader (IS));6String str =br.readline ();7 System.out.println (str);8 br.close ();9 is.close ();Ten socket.close (); One}

Execution Result:

Hello, you received a blessing from the service side of the Mid-Autumn festival

1, the above shows a simple server and client communication process.

2, we introduce this process in detail through the interactive diagram:

3, first on the server side, specify the port number to create the ServerSocket object, through the ServerSocket Accpet method to obtain the socket, this method is characterized by: listen and accept the connection to this socket, this method is blocked before the connection is passed in. This means that if there are no client connection requests coming up, the server will be stuck in the same place.

4, the following code is through socket socket can get input and output stream, so far, is the content of I/O.

5, on the client side, through the specified server hostname and server listening port number, the socket socket, this time indicates that the service side and the client connection has been established, and then through the input and output stream to communicate.

three, half closed sockets

In the demo above, we are the smallest unit of data that is used as a line of communication, and the server is processed on a line-by-row basis. However, in most scenarios, the data unit of the communication is multi-line, and how the output stream of the socket is expressed is ended?

As mentioned in the IO learning process, how to indicate that the output has ended is achieved by turning off the output stream, but not in the socket, because closing the socket will prevent the data from being read from the socket. To solve this problem, Java provides two semi-closed methods:

1, Shutdowninput (): Close the input stream of the socket, the program can also output data through the socket output stream.

2. Shutdownoutput (): Closes the output stream of the socket, and the program can read the data through the socket's input stream.

If we call the Shutdowninput and Shutdownoutput methods on the same socket instance successively, the socket instance is still not closed, except that the socket can neither output data nor read data.

Server-side:

1ServerSocket SS =NewServerSocket (5555);2Socket socket =ss.accept ();3PrintStream PS =NewPrintStream (Socket.getoutputstream ());4PS.PRINTLN ("Server side: Open source China Hangzhou Forum");5PS.PRINTLN ("Server side: Hangzhou G20 Summit");6         //closes the output stream, indicating that the output has ended7 socket.shutdownoutput ();8         //determine if the socket is closed9 System.out.println (socket.isclosed ());TenScanner scan =NewScanner ((Socket.getinputstream ())); One          while(Scan.hasnextline ()) A         { - System.out.println (Scan.nextline ()); -         } the scan.close (); - socket.close (); - ss.close (); -          +     

Client:

1Socket s =NewSocket ("localhost", 5555);2InputStream is =S.getinputstream ();3         byte[] buffer =New byte[1024];4         intFlag = 0;5          while( -1! = (flag = Is.read (buffer,0, Buffer.length )))6         {7String str =NewString (buffer,0, flag);8 System.out.print (str);9         }TenPrintStream PS =NewPrintStream (S.getoutputstream ()); OnePS.PRINTLN ("Client: Welcome to open Source Forum in China"); APS.PRINTLN ("Client: Welcome to the G20 Summit"); - is.close (); - ps.close (); the s.close (); -     

Execution Result:

 

As you can see in the server-side program, after outputting the two-segment string, the Shutdownoutput method is called, indicating that the output has ended. The socket is then judged to be closed, and the result of execution is false, indicating that the socket is not closed.

  However, after the two semi-closed method is called to close the output input stream, the socket cannot open the output stream or the input stream again. Therefore, this scenario is not suitable for maintaining the interactive use of persistent communication State, Only suitable for one-stop communication protocols. For example, the HTTP protocol: After the client connects to the server, it begins to send the data, it is not necessary to send the data again after the sending is completed, only the server response data can be read, and after the data is read, the socket connection is closed.

Iv. network programming based on UDP protocol

The socket programming described above is based on the TCP protocol, now look at the UDP protocol-based programming, TCP and UDP differences in the previous chapter has been introduced.

The main function of the UDP protocol is to complete the transformation between the network data stream and the datagram-----at the transmitting end of the information, the UDP protocol encapsulates the network data stream into the datagram, then sends the datagram, and at the receiving end of the information, the UDP protocol transforms the datagram into the actual datagram content.

1, first in the UDP network programming does not have the server side and the client this kind of argument, the two socket does not have the virtual link, only receives and sends the data message only.

2, there are two important classes: Datagramsocket and Datagrampacket. The former is the socket used to send and receive packets, which represents the packet, and each message is routed from one machine to another based only on the information contained in the package.

3, the Datagramsocket two constructors:

DatagramSocket():构造数据报套接字并将其绑定到本地主机上任何可用的端口。

DatagramSocket(int port):创建数据报套接字并将其绑定到本地主机上的指定端口。

In our demo below, the Udpservertest class first sends the datagram, uses the socket's parameterless constructor, and the Udpclienttest class first receives the datagram, must listen to a certain port, so uses the socket's parameter constructor.

4,Datagrampacket: The time of creation is divided into receive and send two kinds of

DatagramPacket(byte[] buf, int length):用来接收长度为 length 的数据包。

DatagramPacket(byte[] buf, int length, InetAddress address, int port):用来将长度为 length 的包发送到指定主机上的指定端口号。

1  Public classudpservertest2 {3      Public Static voidMain (string[] args)throwsIOException4     {5Datagramsocket ds =NewDatagramsocket ();6String str = "Hello World";7         //constructs a packet for sending, specifying the host and port number8Datagrampacket packet =NewDatagrampacket (Str.getbytes (),9Str.length (), Inetaddress.getbyname ("localhost"), 5555);Ten ds.send (packet); One          A         //read the response sent from the client -         byte[] buffer =New byte[1024]; -Datagrampacket Packet2 =NewDatagrampacket (buffer,buffer.length); the ds.receive (Packet2); -String str2 =NewString (buffer,0, Packet2.getlength ()); - System.out.println (str2); - ds.close (); +     } -}
 Public classudpclienttest{ Public Static voidMain (string[] args)throwsException {datagramsocket ds=NewDatagramsocket (5555); byte[] buffer =New byte[1024]; Datagrampacket Packet=Newdatagrampacket (buffer, buffer.length);        Ds.receive (packet); String Str=NewString (buffer, 0, Packet.getlength ());        System.out.println (str); //after receiving the packet, the client returns a response backString str2 = "Welcome"; Datagrampacket Packet2=NewDatagrampacket (Str2.getbytes (), str2. Length (), packet.getaddress (), Packet.getport ());        Ds.send (Packet2);    Ds.close (); }}

Execution process:

1, the above program, the first step is the server side (in this name to distinguish between the two classes) to create a UDP socket, There is no specified port, using the system assigned to the port. It then constructs a packet that specifies the IP and port number of the target machine.

2, as a client, a UDP socket is created, and the port is bound, if you want to receive packets sent over the server, the bound port must be the same as the port specified in the packet sent by the servers.

3. After the client prints the contents of the package, it wants to return some content back. At this point, the server-side IP and port numbers can be obtained from the packets that were previously sent.

Datagrampacket Packet2 = new Datagrampacket (Str2.getbytes (), Str2.length (), packet.getaddress (), Packet.getport () );

4, when the server receives the packet, it is no longer necessary to bind the port as the client creates the socket, because the port currently listening is the same as the port specified in the packet sent by the client.

5, print to see the server-side IP and listening port number:

ServerIP =/127.0.0.1;serverport=62965

6, wherein the Datagramsocket receive (Datagrampacket p) method is blocked until the packet is received.

Java Network Programming II: Socket detailed

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.