Read the Socket programming in Java and understand the logging ocket

Source: Internet
Author: User

Read the Socket programming in Java and understand the logging ocket

 

Socket, also known as Socket, is one of the basic technologies of computer network communication. Nowadays, most network-based software, such as browsers, instant messaging tools, and even P2P downloads, are implemented based on sockets. This article describes Socket programming based on TCP/IP and how to write a client/server program.

Pre-dinner dessert

The Unix input/output (IO) system follows the operation template such as Open-Read-Write-Close. Before a user process performs an I/O operation, it needs to call Open to specify and obtain the permission to read or write files or devices to be operated. Once an I/O operation object is opened, the user process can read or write the object one or more times. The Read operation is used to Read data from the IO operation object and transmit the data to the user process. The Write operation is used to transmit (Write) data in a user process to an IO operation object. After all the Read and Write operations are completed, the user process needs to call Close to notify the system of its use of the IO object.

When Unix starts to support InterProcess Communication (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 be read and written. The IO descriptor can be a file, device, or communication channel (socket ). A file descriptor consists of three parts: Create (Open socket), read and write data (accept and send to socket), and destroy (close socket ).

In Unix systems, BSD-like IPC interfaces are implemented as a layer above TCP and UDP protocols. The Message destination is represented by a socket address. A socket address is a communication identifier consisting of a network address and a port number.

Inter-process communication requires a pair of sockets. Inter-process communication is completed through data transmission between one socket in one process and another socket in another process. After a message is executed and sent, the message is queued in the socket at the sending end until the underlying network protocol sends the message. When a message arrives at the receiving end's socket, it will also be in the queue until the receiving end's process receives the message.

TCP and UDP Communication

We have two communication protocols for socket programming. One is datagram communication, and the other is stream communication.

Datagram Communication

The datagram communication Protocol (UDP) is a commonly used Protocol ). UDP is a connectionless protocol, which means that each time we send a data report, we need to send both the local socket Descriptor and the socket descriptor at the receiving end. Therefore, we need to send additional data for each communication.

Stream Communication

The stream communication Protocol, also known as TCP (Transfer Control Protocol ). Unlike UDP, TCP is a connection-based protocol. Before using stream communication, we must establish a connection between one pair of sockets for communication. One socket serves as the server to listen for connection requests. The other is used as the client for connection requests. Once the two sockets have established a connection, they can transmit data in one or two directions.

Read this, we have many such questions, we use UDP or TCP for socket programming. The protocol-based socket programming depends on your specific client-server application scenario. Next we will analyze the differences between TCP and UDP, which may help you better choose which Protocol to use.

In UDP, each time a data report is sent, the local socket Descriptor and the receiver socket descriptor must be attached. Because TCP is a connection-based protocol, a connection needs to be established before communication between socket pairs. Therefore, the time consumed for establishing a connection exists in TCP socket programming.

In UDP, the maximum data size is 64 KB. This restriction does not exist in TCP. Once the socket pair of TCP Communication establishes a connection, the communication between them is similar to the IO stream, and all the data will be read in the order of receipt.

UDP is an unreliable protocol. The sent data packets may not be accepted by the socket at the receiving end in the sending order. TCP is a reliable protocol. The order of packets received by the receiving end is the same as that of packets received by the sending end.

In short, TCP is suitable for network services such as remote Logon (rlogin, telnet) and file transfer (FTP. Because the size of the data to be transmitted is unknown. UDP is simpler and lighter than TCP. UDP is used for services with high real-time performance or unimportant packet loss. UDP packet loss rate in LAN is relatively low.

Socket programming in Java

The following sections illustrate how to use socket to write the client and server programs.

Note: In the following example, I will use socket programming based on TCP/IP protocol, because this protocol is far more widely used than UDP/IP. All socket-related classes are in the java.net package, so we need to introduce this package during socket programming.

Enable Socket in client writing

If you are on the client, you need to write 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, the host is the machine that the client needs to connect to, and the port is the port used by the server to listen to the request. When selecting a port, note that it is 0 ~ 1023 these ports have been reserved by the system. These ports are used by common services, such as email, FTP, and HTTP. When you compile the server code and select a 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's socket object, and then write the data. It is similar to the 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

Similar to file IO, after reading and writing data, we need to close the IO object to ensure the correct release of resources.

Write a socket on the server
int port = 8919;ServerSocket server = new ServerSocket(port);Socket socket = server.accept();

The above Code creates a server socket, and then calls the accept method to listen and obtain the client request socket. The accept method is a blocking method that waits for blocking until the connection is established between the server and the client.

Read data

Obtain the InputStream object through the socket object obtained above, and then read the data like the installation file IO. 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

You must close the IO object correctly to ensure the correct release of the resource.

Example

Here we add an example to use socket to implement an echo server, that is, the server will send the data sent from the client back to the client. The code is simple.

import java.io.*;import java.net.*;public class EchoServer {    public static void main(String args[]) {        // declaration section:        // declare a server socket and a client socket for the server        // declare an input and an output stream        ServerSocket echoServer = null;        String line;        DataInputStream is;        PrintStream os;        Socket clientSocket = null;        // Try to open a server socket on port 9999        // Note that we can't choose a port less than 1023 if we are 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 code above and make the following request to view the data carried by the client request.

 
15:00 $ curl http://127.0.0.1:9999/?111GET /?111 HTTP/1.1User-Agent: curl/7.37.1Host: 127.0.0.1:9999Accept: */*
Summary

Client-server-side programming is interesting, and socket programming in Java is easier and faster than other languages (such as C.

The java.net package contains many powerful and flexible classes for developers to perform network programming. In network programming, we recommend that you use the APIS under this package. Sun. * This package also contains many network programming-related classes, but we do not recommend using the APIS under this package, because this package may change, in addition, this package cannot be included on all platforms.

Original information
  • Original article address: Sockets programming in Java: A tutorial

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.