Read socket programming in Java

Source: Internet
Author: User

Socket, also known as socket, socket is one of the basic technologies of computer network communication. Today, most web-based software, such as browsers, instant messaging, and even peer-download, is based on sockets. This article describes TCP/IP-based socket programming and how to write a client/server program.

Pre-dinner Dessert

The UNIX input-output (IO) system follows the Open-read-write-close model. Before a user process makes an IO operation, it needs to call open to specify and obtain the permission to be read or written by the file or device to be manipulated. Once an IO operation object is opened, the user process can read or write to the object one or more times. The read operation is used to read data from an IO operand and pass the data to the user process. The write operation is used to pass (write) data from the user's process to the IO action object. When all the read and write operations are finished, the user process needs to call close to notify the system of its completion of the use of the IO object.

When Unix begins to support interprocess communication (interprocess communication, or IPC), the IPC interface is designed to be similar to the file IO operation interface. In Unix, a process has a set of IO descriptors that can read and write. The IO descriptor can be a file, a device, or a communication channel (socket socket). A file descriptor consists of three parts: create (open socket), read write data (accept and send to socket) and destroy (Close socket).

In Unix systems, the BSD-like version of the IPC interface is implemented as a layer above the TCP and UDP protocols. The destination of the message is represented using the socket address. A socket address is a communication identifier that consists of a network address and a port number.

An inter-process communication operation requires a pair of sockets. interprocess communication is done by transferring data from one socket to another in one process to another. When a message executes, the message is queued in the socket on the sending side until the underlying network protocol sends the messages. When the message arrives at the receiving end of the socket, it is also queued until the receiving side processes the message.

TCP and UDP communication

About socket programming There are two types of communication protocols that can be selected. One is the datagram communication, the other is the circulating letter.

Datagram Communication

The datagram communication protocol is what we often call UDP (user Data Protocol Subscriber Datagram Protocol). UDP is a non-connected protocol, which means that each time we send a datagram, we need to send both the socket descriptor of the machine and the socket descriptor at the receiving end. Therefore, we need to send extra data each time we communicate.

Stream communication

The stream communication protocol, also known as TCP (Transfer Control Protocol, Transmission protocol). Unlike UDP, TCP is a connection-based protocol. Before using a flow of letters, we must establish a connection between the communication's pair of sockets. One of the sockets listens for connection requests as a server. The other is a connection request as a client. Once the two sockets have been established, they can transmit data in one or both directions.

Read here, how much we have this question, we do socket programming using UDP or TCP it. The choice of the protocol based socket programming depends on your specific client-server application scenario. Let's briefly analyze the differences between TCP and UDP protocols, perhaps to help you better choose which one to use.

In UDP, each time a datagram is sent, it needs to be accompanied by the socket descriptor on the computer and the socket descriptor on the receiving side. Because TCP is a connection-based protocol, there is a need to establish a connection between the socket pairs of the communication before the communication, so there is a time-consuming socket programming that exists in the TCP protocol.

In UDP, datagram data has a 64KB limit on size. There is no such restriction in TCP. Once the TCP communication socket pair establishes a connection, the communication between them is similar to the IO stream, and all the data is read in the order in which it was received.

UDP is an unreliable protocol that sends datagrams that are not necessarily accepted by the socket at the receiving end in the order in which they are sent. Then TCP is a reliable protocol. The order of packets received by the receiving end is consistent with the order of the packets on the sending side.

In short, TCP is suitable for network services such as remote login (rlogin,telnet) and file Transfer (FTP). Because the size of the data that needs to be transferred is indeterminate. UDP is simpler and lighter than TCP. UDP is used to achieve higher real-time or packet loss is not important for some services. UDP packet loss rate is relatively low in LAN.

Socket programming in Java

In the following sections I'll walk through some examples of how to write client and server-side programs using sockets.

Note: In the next example, I will use the TCP/IP protocol-based socket programming because this protocol is far more extensive than UDP/IP. And all of the socket related classes are located under the package, so we need to introduce this package when we do socket programming.

Client Write Open socket

If on the client side, you need to write down the following code to open a socket.

String host = ""; int port = 8919new  Socket (host, port);

In the above code, host is the machine that the client needs to connect to, and port is the one on the server that listens for requests. When choosing a port, it is important to note that 0~1023 these ports are already reserved by the system. These ports are used by a number of commonly used services, such as mail, FTP, and HTTP. When you are writing server-side code, select the port, select a port greater than 1023.

Write Data

The next step is to write the request data, we get the OutputStream object from the client socket object, and then write the data. Very similar to file IO processing code.

 Public classClientsocket { Public Static voidMain (String args[]) {string host= ""; intPort = 8919; Try{Socket Client=NewSocket (host, Port); Writer writer=NewOutputStreamWriter (Client.getoutputstream ()); Writer.write ("Hello from Client");          Writer.flush ();          Writer.close ();        Client.close (); } Catch(IOException e) {e.printstacktrace (); }    }  }
Close IO Object

Like file Io, after the read and write data is completed, we need to close the IO object to ensure the correct release of the resource.

Server-side write open the server-side socket
int port = 8919new= server.accept ();

The above code creates a server-side socket, and then calls the Accept method to listen and get the client's request socket. The Accept method is a blocking method that waits for blocking until a connection is established between the server side and the client.

Reading data

Get the InputStream object from the socket object above and then install file IO to read the data. Here we print out the content.

 Public classserverclient { Public Static voidMain (string[] args) {intPort = 8919; Try{serversocket server=NewServerSocket (port); Socket Socket=server.accept (); Reader Reader=NewInputStreamReader (Socket.getinputstream ()); CharChars[] =New Char[1024]; intLen; StringBuilder Builder=NewStringBuilder ();  while(( (chars))! =-1) {builder.append (NewString (chars, 0, Len)); } System.out.println ("Receive from client message=:" +builder);            Reader.close ();            Socket.close ();        Server.close (); } Catch(Exception e) {e.printstacktrace (); }  }}
Close IO Object

Still cannot be forgotten, finally need to close the IO object properly to ensure the correct release of resources.

An example of a note

Here we add an example, using a socket to implement an echo server, that is, the server will send the data sent by the client back to the client. The code is simple.*;*; Public classEchoserver { Public Static voidMain (String args[]) {//Declaration section://declare a server socket and a client socket for the server//declare an input and an output streamServerSocket Echoserver =NULL;        String Line;        DataInputStream is;        PrintStream OS; Socket Clientsocket=NULL; //Try to open a server sockets on port 9999//Note that we can ' t choose a port less than 1023 if we is not//privileged Users (root)        Try{echoserver=NewServerSocket (9999); }        Catch(IOException e) {System.out.println (e); }        //Create A Socket object from the ServerSocket to listen and accept//connections. //Open input and output streams        Try{Clientsocket=echoserver.accept (); is=NewDataInputStream (Clientsocket.getinputstream ()); OS=NewPrintStream (Clientsocket.getoutputstream ()); //as long as we receive data, echo that data back to the client.                while(true) { line=Is.readline ();               Os.println (line); }        } Catch(IOException e) {System.out.println (e); }        }}

Compile and run the above code, make the following request, you can see the contents of the data that the client requested to carry.

: $ Curl 111 http/1.1User-agent:curl/7.37. 1  127.0. 0.1:9999* /*

Client-server programming is interesting, and socket programming in Java is easier and faster to write than other languages such as C. This package contains a lot of powerful and flexible classes for developers to network programming, in the network programming, it is recommended to use the following API in this package. At the same time sun.* This package also contains a lot of network programming related classes, but it is not recommended to use the package below the API, because this package may change, and this package is not guaranteed to be included in all platforms.

Source information
    • Original address: Sockets Programming in JAVA:A Tutorial

Read socket programming in Java

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: 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.