Day twenty-eight

Socket socket

Socket TCP-based protocol

Streaming protocol, stream-oriented communication message protection is no boundary

Data will be less, the short time interval of data transmitted disposable packing

Reliable but stick package: the data will not be lost, confiscated complete package, will continue to the last continue to receive data. The data are reliable

Only TCP packet sticky phenomenon

 

Stick package problem

 

Causes: 1 small data transmission, a time period, TCP session will automatically synthesized data, resulting in stick package. (Sender's caching mechanism).

      2. Receive data to receive only part of the next will continue to receive the last received data. (Recipient cache mechanism)

 

 

It occurs only in the TCP protocol.

 

Root of the problem:

 

The recipient does not know the size of the message

 

solution:

1. The size of the data transmission provided by

2. The use of the struct module calls .pack header transmission header length packed

3. The call recipient using struct .unpack unpacking header length header removed

 

Case: subprocess using the analog input terminal command

'' ' 
Clients                                      

1, connected to the service                                                                                             
2, the command transmission                                                                                            
3, the received header header                             
4, struct.unpack header length of the header to obtain the dictionary       
5, using the length of the received dictionary dictionary                       
6, the length of real data out the dictionary                     
7, subsection receiving real data    
'' '                        
'' ' 
Server: 

1, open the service                                                           
2, the command receiving client                                                           
3 using the command returns a result subprocess res 
. 4, res data dictionary structure 
5, the sequence of the dictionary, the dictionary obtained serialized length 
6, using struct module the length of the header structure dictionary head 
7, the first transmission header 
8, transmit the dictionary 
9, actual data transmission 
'' '

 

 

 

client.py:

import socket
import struct
import json


IP = '127.0.0.1'
PORT = 8001

client = socket.socket()
client.connect((IP, PORT))

while True:
    cmd = input('>>>').strip()
    client.send(cmd.encode('utf-8'))
    # 接收字典报头
    data = client.recv(4)
    dict_size = struct.unpack('i', data)[0]
    # 接收字典数据
    dict_data = client.recv(dict_size)
    dic = json.loads(dict_data.decode('utf-8'))
    # 取出数据长度
    file_size = dic.get('file_size')
    #接收真实数据
    recv_size = 0
    real_data = b''
    while recv_size < file_size:
        data = client.recv(1024)
        real_data += data
        recv_size += len(data)

    print(real_data.decode('utf-8'))

 

 

server.py

import socket
import subprocess
import struct
import json

IP = '127.0.0.1'
PORT = 8001

server = socket.socket()
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind((IP, PORT))
server.listen(5)

while True:
    conn, addr = server.accept()
    while True:
        try:
            print('客户端地址:', addr)
            cmd = conn.recv(1024)
            obj = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            res = obj.stdout.read() + obj.stderr.read()

            # 构造一个字典
            dic = {'name': 'jason', 'file_size': len(res), 'info': 'great'}
            dump_dict = json.dumps(dic)

            # 制作字典报头
            header = struct.pack('i', len(dump_dict))
            # 发送字典报头
            conn.send(header)
            # 发送字典
            conn.send(dump_dict.encode('utf-8'))
            # 发送真实数据
            conn.send(res)
        except ConnectionResetError as e:
            break

    conn.close()

 

Guess you like

Origin www.cnblogs.com/AbrahamChen/p/11323021.html