@ the Author: Runsen

TCP/IP

For two lovers to fall in love and communicate with each other, there must be rules on both sides. In the same way, communication between different hardware and operating systems requires a rule. This rule is called a protocol.

TCP/IP is the general name of various internet-related protocol families. TCP/IP refers to TCP and IP. TCP/IP refers to the protocol family used in IP communication.

The TCP/IP protocol family is divided into application layer, transport layer, network layer, data link layer, and physical layer. It can be divided into 4 or 7 layers, depending on the model.

TCP/IP is divided into five layers, closer to the hardware as you go down.

Application layer: after the application receives the data of the transmission layer, it is necessary to interpret it. The interpretation must be in good format first, and the application layer is to specify the data format of the application program. The main protocol is HTTP and so on.

Transport layer: This layer provides end-to-end communication between applications on two hosts. The transport layer has two transport protocols: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). TCP is a reliable connection-oriented protocol, while UDP is an unreliable or connectionless protocol.

The network layer: determines how data is transferred from sender to receiver and establishes host-to-host communication.

Data link layer: Controls the communication between the network layer and the physical layer to ensure reliable data transfer on the physical line.

Physical layer: This layer is responsible for the physical transport, related to the link, but also related to the transmission medium.

Client and server specific

The image is from the Illustrated HTTP book

Three handshakes, four waves

TCP three times shake hands, four times wave, Runsen also can’t say how, put the most popular picture on the Internet below, or don’t look at me very cool, cool is the big guy who makes the picture.

Three-way handshake

Four times to wave

The picture comes from the public account (programmer little Brook), more nouns and concepts to find the reference to the public account programmer little Brook article ~

Socket

Network programming has an important concept of sockets, through which applications can send or receive data, and sockets allow applications to insert I/O into the network and communicate with other applications in the network.

I came to peek at the Network communication Socket in Python and accidentally peek at a very nice Socket image

Arrange the steps in the above picture

1. Establish a connection:

  • Server: socket >address >bind >listen > Accept

  • Client: socket– >connect

2. Communication: Received: RECV (1024)<– send(byte)/sendall(byte)

3. Close the connection: close()

Implement simple communication procedures

Server side, server.py

Create a socket or use server = socket.socket()
server = socket.socket(socket.AF_INET, socket.SOCK_STREAMIp_port = (');127.0.0.1', 8888) # bind listener:bind(address), under AF_INET, represents the address server in the form of a tuple (IP,port).bind(ip_port) # Set the maximum number of connections1
server.listen(5) # accept connections continuously: one by one while True:print("Waiting for data connection..."Conn = conn, address = serveraccept(a)' ''Return message to customer service (note: python3.x, network data is sent and received in byte type, send and receive String data need to be encoded (send: messages.enconde(); Return to String :messages.deconde()), pyhon2.x sends data without encoding) '' '
    messages = "Connection successful!"
    conn.send(messages.encode() # count = count =0While True: data = connrecv(1024Print the data message sent by the clientprint(data.decodeIf data == b; if data == b'exit': break # Process client data (e.g., respond to requests, etc.) count = count +1
        string = "The first" + str(count) + "Message:" + data.decode()
        conn.send(string.encode() # close the connection to conn.close(a)Copy the code

Client, client.py

Import socket # Create socket client = socket.socketIp_port = (" ")127.0.0.1", 8888# connect to server host client.connect(ip_port) # While True: # Receive the data sent or responded by the server data = client.recv(1024) # print the received data; Python3. x above data to be encoded (send: data.enconde(a); After receiving the data, it is converted to a String :data.deconde())
    print(data.decode())
    messages = input("Please enter occurred or requested data (exit exit) :")
    client.send(messages.encode())
    if messages == 'exit':
        break
    ' 'Data = client.recv(1024) # print received data; Python3. x to encode data above python3.x, send enconde(); Receive deconde() print(data.decode()) '' '# Close the connection to client.close(a)Copy the code

The specific effect is shown in the figure below.

Multithreaded communication

The TCP server communicates with multiple TCP clients at the same time. You can create the handle_client task through threading.

Import socket import threading import random def handle_client(): address = serveraccept(a)print("[*] Accept connection from: %s:%d" % (address[0], address[1]))
    messages = "Hello World!"
    client.send(messages.encode()) # connect to the current client while True:recv(1024)).decode() # request =='exit':
            break
        print("[*] Received from %s:%d : %s" % (address[0], address[1], request)) # send a response message to the client.send((str(random.randint(1.1000)) + ":" + "ACK!").encode() # close the current connection to the client.close()


if __name__ == "__main__"Create a socket server = socketsocket(socket.AF_INET, socket.SOCK_STREAM) # define binding IP and port IP ='127.0.0.1'
    port = 8888# bind listener server.bind((IP, port)) # set the maximum number of connections1
    server.listen(5)
    print("[*] Listening on %s:%d"% (IP, port)) # loop to start a thread that accepts communication from multiple clients.Thread(target=handle_client) # Enable client_handler.start(a)Copy the code

After python3.x is used, network data messages are sent and received in byte format. To send and receive String data, you need to encode the data using messages.enconde(). After receiving the data, you need to convert the data to String using messages.deconde(). Pyhon2. x sends data directly without encoding.

GitHub, portal ~, GitHub, portal ~, GitHub, Portal ~