The ins and outs of sockets

The following analysis is mainly referred to the computer network (Xie Xiren 7th edition) to summarize, from the system call -> application programming interface API- > Socket interface to analyze the ins and outs of Socket, of course wikipedia also has a detailed explanation of Socket

1. System call

Most operating systems use the mechanism of system calls to transfer control between applications and the operating system. To programmers, system calls are very similar to function calls in normal programming

2. Application Programming Interface apis

When an application process initiates a system call, control is transferred from the application process to the system call interface, which in turn passes control to the computer’s operating system. The operating system forwards this call to an internal procedure and performs the requested action. Once the internal process is executed, control is returned to the application process through the system call interface.

System call interface is actually an interface that transforms the control rights of application process and operating system, namely application programming interface (API)

3. The socket

Because the TCP/IP protocol family is designed to run on multiple operating systems, the TCP/IP standard allows system designers to choose implementation details about the API.

Currently, the most famous application programming interface API available to applications using TCP/IP is the socket interface

A socket is not a physical entity, but an abstraction, and a socket is a data structure that provides applications to create and use

4. Socket descriptor

When an application process (client or server) needs to use the network to communicate, it must first issue a socket system call to request the operating system to create a “socket” for it. The effect of this call is to ask the operating system to allocate some of the system resources (memory space, CPU time, network bandwidth, etc.) needed for network communication to the application process.

The operating system represents the sum of these resources in a number (small integer) called a socket descriptor, and returns this socket descriptor to the application process.

Socket communication icon

As can be seen from the figure, Socket communication is inseparable from TCP/IP. To enable host A and host B to communicate, A Socket connection must be established. The Socket connection must be established through the underlying TCP/IP protocol.

Socket communication protocol analysis

As mentioned above, Socket communication and TCP/IP protocol is closely related, about Socket programming communication we have two protocols to choose from, that is the common TCP protocol and UDP protocol

UDP protocol.

UDP is a connectionless protocol, also known as datagram protocol. Each time a datagram is sent, both the local socket descriptor (the socket descriptor described above) and the socket descriptor on the receiving end are sent. So, each communication sends additional data.

TCP protocol

TCP is a protocol with connections. TCP connections must be established before applications can be used. So each time before the communication, we need to establish a Socket connection, one Socket as the server to listen to the request, the other Socket as the client to connect the request. Only after the two sides establish a good connection, the two sides can communicate.

Differences and choices between the two protocols

A brief analysis of the differences between the two:

  • In UDP, each time a datagram is sent, both the local socket descriptor and the socket descriptor of the receiver are attached. TCP is a connection-based protocol. A connection needs to be established before communication between sockets, that is, TCP three-way handshake. Therefore, establishing a connection takes some time
  • In UDP, datagram data is limited in size to 64KB. TCP does not have this limitation. Once TCP communication socket pairs establish connections, they communicate like I/O streams.
  • UDP is an unreliable protocol. Datagrams sent may not be received by the socket at the receiving end in the order in which they are sent. TCP is a reliable protocol. The order of packets received by the receiver is roughly the same as the order of packets received by the sender (packet loss is not discussed here).

Speaking of which, as to choose which protocol, or depending on your use scenario, of course, the current more see is based on TCP protocol Socket communication. Of course, some real-time higher some services, LAN some services with UDP more.

Based on TCP protocol Java Socket programming example

Socket programming is generally divided into 3 steps: establish a connection, data transfer, connection release. Of course, the specific steps of the server and client programs are somewhat different, as shown in the figure above.

Here we use the Java.NET package ServerSocket class (mainly for the server) and Socket class (for establishing connections) to implement a Socket communication instance

Server-side writing

package com.pjmike.Socket;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;

/** * server **@author pjmike
 * @createThe 2018-08-12 17:43 * /
public class Server {
    private ServerSocket serverSocket = null;
    private Socket socket = null;
    private DataInputStream input = null;

    public Server(int port) {
        try {
            // Bind ports
            System.out.println("bind port ...");
            serverSocket = new ServerSocket(port);
            System.out.println("Server started and waiting a client ..");
            // Call accept() to extract the connection request
            socket = serverSocket.accept();
            // Usually in bytes
            input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            String line = "";
            while(! line.equals("exit")) {
                try {
                    // The readUTF() method reads the data written by writeUTF()
                    line = input.readUTF();
                    System.out.println("recd: " + line);
                } catch(IOException o) { o.printStackTrace(); }}// Close the connection
            System.out.println("connection closed ...");
            input.close();
            socket.close();
        } catch(IOException e) { e.printStackTrace(); }}public static void main(String[] args) {
        Server server = new Server(5000); }}Copy the code

Client program

package com.pjmike.Socket;

import java.io.*;
import java.net.Socket;
import java.nio.Buffer;

/** * client **@author pjmike
 * @createThe 2018-08-12 men of * /
public class Client {
    private Socket socket = null;
    private DataOutputStream output = null;
    private BufferedReader input = null;

    public Client(String address, int port) {
        try {
            // Establish a connection
            socket = new Socket(address, port);
            System.out.println("Connected ...");
            // Enter information from the console
            input = new BufferedReader(new InputStreamReader(System.in));
            output = new DataOutputStream(socket.getOutputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
        String line = "";
        while(! line.equals("exit")) {
            try {
                line = input.readLine();
                System.out.println("The client input is:"+line);
                output.writeUTF(line);
            } catch(IOException e) { e.printStackTrace(); }}try {
            input.close();
            socket.close();
            output.close();
        } catch(IOException e) { e.printStackTrace(); }}public static void main(String[] args) {
        Client client = new Client("localhost".5000); }}Copy the code

test

The client

Connected ... Hello world: nihao: Hello world nihao: NihaoexitThe client input is:exit
Copy the code

The service side

bind port ...
Server started and waiting a client ..
recd: hello world
recd: nihao
recd: exit
connection closed ...

Copy the code

Of course, sometimes we need more than one client to connect to the same server, this is not difficult to use multi-threaded way, let the server loop call accept() method, each client request to open a thread for processing.

summary

In fact, Socket is a communication mechanism between processes. In Java Socket programming, there are also three steps: establishing communication links, data transmission, and link closure. Network programming is closely integrated with Java I/O operations, and familiarity with I/O operations is essential.

The resources

  • Take an in-depth look at how Java I/O works
  • Read Socket programming in Java
  • Java tutorial: Sockets programming
  • Computer Networks (Xie Xiren 7th Edition)