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 java.net package, so we need to introduce this package when we do socket programming.
Client Writing
Open socket
If on the client side, you need to write down the following code to open a socket.
String host = "127.0.0.1"; int port = 8919; Socket client = new 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 class Clientsocket {public static void main (string args[]) { string host = "127.0.0.1"; int port = 8919; Try { Socket client = new socket (host, port); Writer writer = new OutputStreamWriter (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 Authoring
Open the server-side socket
int port = 8919; ServerSocket Server = new ServerSocket (port); Socket socket = 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 class Serverclient {public static void Main (string[] args) { int port = 8919; try { ServerSocket server = new ServerSocket (port); Socket socket = server.accept (); Reader reader = new InputStreamReader (Socket.getinputstream ()); Char chars[] = new char[1024]; int Len; StringBuilder builder = new StringBuilder (); while ((Len=reader.read (chars))! =-1) { builder.append (new String (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.
Import Java.io.*;import java.net.*;p ublic class Echoserver {public static void main (String args[]) {//Declara tion section://Declare a server sockets and a client socket for the server//declare an input and an OUTPU T stream serversocket echoserver = null; String Line; DataInputStream is; PrintStream OS; Socket clientsocket = null; Try toopen a server socket on port 9999//Note so we can ' t choose a port less than 1 023 If we is not//privileged users (Root) try {echoserver = new ServerSocket (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 = new DataInputStream (Clientsocket.getinputstream ()); OS = new PrintStream (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.
15:00 $ curl Http://127.0.0.1:9999/?111GET/?111 http/1.1user-agent:curl/7.37.1host:127.0.0.1:9999accept: */*
Summarize
Client- Server programming is interesting, and socket programming in Java is easier and faster to write than other languages such as C.
Java.net 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.
Original address: Sockets Programming in JAVA:A Tutorial
QQ Group: Web Developer Official Group (321386971) authentication message: Admin10000
Read socket programming in Java