Introduction

Whether in ordinary network programming or in netty, a word called socket is often mentioned, as if socket is a magical thing, using socket we can establish a connection from client to server, and communicate with client and server End-to-end communication, so what exactly is a socket? What categories does it have? Let's take a look together.

what is socket

The Chinese translation of socket is socket. Personally, this translation is really bad. Socket sounds meaningless, so many people must be confused when they hear the word socket for the first time.

So what is a socket? Socket is a method of process communication between different programs, these programs can be on the same server or on different servers.

The basis for socket establishment of connection is the IP protocol, which is used to encapsulate and group data before it can be transmitted on the network. This kind of socket that depends on the IP protocol is also called a network socket.

The connection between the client and the server can be established through the network socket, and the client and the server discover each other through the socket address.

Taking java as an example, let's take a look at the definition of SocketAddress:

 public abstract class SocketAddress implements java.io.Serializable {

    static final long serialVersionUID = 5215720748342549866L;

}

It can be seen that SocketAddress is only a general definition. It can have multiple implementations. Its specific implementation includes a transmission protocol, such as TCP or UDP, and also needs to include an IP address and a connection port.

The IP address and port define the connection object, and the protocol defines the connection method.

Based on different protocols, different types of sockets can be derived. For example, those that rely on the TCP protocol are called Stream sockets, those that rely on the UDP protocol are called Datagram sockets, and those that rely on local files for data transmission are called Unix Domain Sockets.

Next, we will explain the use of these protocols in detail in a unix system.

Before explaining the detailed example, we need to use the commands related to the network, they are ss, nc and socat.

In this article, I am using centOS system, so you can use the following command to install:

 yum install iproute2 netcat-openbsd socat

Stream Socket

What is Stream Socket? Literally, this Socket connection is used for streaming. If streaming is to be performed, a stable network connection needs to be established first. In terms of stable connection, there is no doubt that TCP (Transmission Control Protocol) ) is the most common and extremely efficient protocol.

For Stream Socket, it is directional. The data package needs to be passed from one address to another through the network, and also needs to receive the processing return result of the other party. In this process, the TCP protocol is usually used.

The TCP protocol can ensure the stability and order of data, and the TCP data packets can guarantee the order of data packets sent to the physical network interface. If the packets received by the network interface are out of order, the network adapter and the operating system will ensure that they are reassembled in the correct order for the application to use.

Common TCP-based Stream Sockets are the http and https services that we often access. The servers handling http and https services are generally nginx or apache, so there are usually the following Stream Socket addresses:

 124.225.141.53:80
124.225.141.53:443

I used the IP address of NetEase above, where 80 means http and 443 means https.

Create a TCP server with socat

Commonly used TCP servers can choose apache or nginx. For the sake of simplicity, we choose to use socat to create a TCP server.

what is socat? It is short for SOCket CAT and can be used to simulate a TCP server.

The command of socat is very complicated, here we just briefly introduce its application:

 socat -h
socat by Gerhard Rieger and contributors - see www.dest-unreach.org
Usage:
socat [options] <bi-address> <bi-address>

From the above results we can see that socat can accept some addresses and then can add some options.

Here we use socat to create two connections, TCP6 and TCP4, socat has two options to do the job:

       tcp-connect:<host>:<port> groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,TCP
      tcp-listen:<port> groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,IP6,TCP
      tcp4-connect:<host>:<port>        groups=FD,SOCKET,CHILD,RETRY,IP4,TCP
      tcp4-listen:<port>        groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,TCP
      tcp6-connect:<host>:<port>        groups=FD,SOCKET,CHILD,RETRY,IP6,TCP
      tcp6-listen:<port>        groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP6,TCP

Here we only need to set up two services listening on TCP, so we use the following command:

 socat TCP4-LISTEN:8888,fork /dev/null&
socat TCP6-LISTEN:8888,ipv6only=1,fork /dev/null&

In the above command, we monitor the connection information of TCP4 and TCP6 on port 8888. The fork parameter indicates that the program will continue to run after receiving the package. If fork is not used, the program will automatically exit.

Socat was originally going to be followed by a bi-address. Here we use /dev/null, which means to discard all income information.

TCP6-LISTEN has a special parameter called ipv6only, which means that received packets should not be sent to IPv4-mapped IPv6 addresses.

What are IPv4-mapped IPv6 addresses? Simply put, it maps IPv4 to IPv6 addresses.

Executing the above command, we will get the following output:

 [1] 30877
[2] 30885

Because it is executed in the background, we return the ID of the process.

Check TCP connection with ss

ss is a very powerful command, we can use ss to monitor the information of TCP sockets, its usage is as follows:

 ss -h
Usage: ss [ OPTIONS ]
       ss [ OPTIONS ] [ FILTER ]

We mainly look at the following parameters that will be used:

    -4, --ipv4          display only IP version 4 sockets
   -6, --ipv6          display only IP version 6 sockets
   -t, --tcp           display only TCP sockets
   -l, --listening     display listening sockets
  -n, --numeric       don't resolve service names

Because we only monitor ipv4 and ipv6 data, here we use the two parameters -4 and -6.

In addition, because you only need to listen to tcp sockets, you need to use the -t parameter.

Because it is listening, the -l parameter is used. Finally, we want to see the specific number instead of being parsed into a service name, so the -n parameter is used here.

Let's use the following command to see the result:

 ss -4 -tln

The result is as follows:

 State       Recv-Q Send-Q                      Local Address:Port                                     Peer Address:Port              

LISTEN      0      5                                       *:8888                                                *:*  

Indicates that port 8888 is being monitored. Of course, if there are other processes on your server, there may be more than this piece of data.

The above command only listens to Ipv4, let's look at Ipv6:

 ss -6 -tln

You might get the following output:

 ss -6 -tln
State       Recv-Q Send-Q                      Local Address:Port                                     Peer Address:Port              

LISTEN      0      5                                      :::8888                                               :::* 

Similar to Ipv4, it means that we are listening on port 8888 on Ipv6.

Use nc to connect socket

Now that we have established a server listening for TCP connections, let's try to connect using the nc command.

nc is short for Ncat and it is a very useful networking tool that can do a lot of things. Let's take a look at the parameters that will be used in this example:

   -4                         Use IPv4 only
  -6                         Use IPv6 only
  -v, --verbose              Set verbosity level (can be used several times)
  -z                         Zero-I/O mode, report connection status only

The -4 and -6 parameters are required because it needs to connect to Ipv4 and Ipv6.

In addition, we need to output detailed information, so the -v parameter is required. Finally, we directly establish the connection without sending any data, so the -z parameter is used here. Let's execute it to see the effect:

 nc -4 -vz 127.0.0.1 8888

Take a look at the output below:

 nc -4 -vz 127.0.0.1 8888
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 127.0.0.1:8888.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.

You can see that nc has successfully established a connection and sent 0 bytes of content.

Likewise, we establish a connection to IPv6:

 nc -6 -vz ::1 8888

Here ::1 represents the local address of IPv6. The output is as follows:

 Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to ::1:8888.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.

Summarize

So far, we have introduced the meaning of the basic classification of Socket, Stream Socket, and used the tools in unix to build a socket server and client. Of course, this is only the simplest description, and you can use it to experience the process of Stream Socket.

This article has been included in http://www.flydean.com/15-stream-socket/

The most popular interpretation, the most profound dry goods, the most concise tutorials, and many tricks you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "Program those things", understand technology, understand you better!


flydean
890 声望433 粉丝

欢迎访问我的个人网站:www.flydean.com