其他分享
首页 > 其他分享> > recv原理、高阶版黏包解决方案、基于UDP的socket通信

recv原理、高阶版黏包解决方案、基于UDP的socket通信

作者:互联网

recv原理、高阶版黏包解决方案、基于UDP的socket通信

recv原理

源码解释:
Receive up to buffersize bytes from the socket.
接收来自socket缓冲区的字节数据,
For the optional flags argument, see the Unix manual.
对于这些设置的参数,可以查看Unix手册。
When no data is available, block untilat least one byte is available or until the remote end is closed.
当缓冲区没有数据可取时,recv会一直处于阻塞状态,直到缓冲区至少有一个字节数据可取,或者远程端关闭。
When the remote end is closed and all data is read, return the empty string.
关闭远程端并读取所有数据后,返回空字符串。
# 1,验证服务端缓冲区数据没有取完,又执行了recv执行,recv会继续取值。
import socket
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
phone.send('hello'.encode('utf-8'))
phone.close()



# 2,验证服务端缓冲区取完了,又执行了recv执行,此时客户端20秒内不关闭的前提下,recv处于阻塞状态。
import socket
import time
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
phone.send('hello'.encode('utf-8'))
time.sleep(20)

phone.close()

# 3,验证服务端缓冲区取完了,又执行了recv执行,此时客户端处于关闭状态,则recv会取到空字符串。
import socket
import time
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
phone.send('hello'.encode('utf-8'))
phone.close()
# 1,验证服务端缓冲区数据没有取完,又执行了recv执行,recv会继续取值。

import socket

phone =socket.socket(socket.AF_INET,socket.SOCK_STREAM)

phone.bind(('127.0.0.1',8080))

phone.listen(5)

conn, client_addr = phone.accept()
from_client_data1 = conn.recv(2)
print(from_client_data1)
from_client_data2 = conn.recv(2)
print(from_client_data2)
from_client_data3 = conn.recv(1)
print(from_client_data3)
conn.close()
phone.close()

# 2,验证服务端缓冲区取完了,又执行了recv执行,此时客户端20秒内不关闭的前提下,recv处于阻塞状态。

import socket

phone =socket.socket(socket.AF_INET,socket.SOCK_STREAM)

phone.bind(('127.0.0.1',8080))

phone.listen(5)

conn, client_addr = phone.accept()
from_client_data = conn.recv(1024)
print(from_client_data)
print(111)
conn.recv(1024) # 此时程序阻塞20秒左右,因为缓冲区的数据取完了,并且20秒内,客户端没有关闭。
print(222)

conn.close()
phone.close()


# 3 验证服务端缓冲区取完了,又执行了recv执行,此时客户端处于关闭状态,则recv会取到空字符串。

import socket

phone =socket.socket(socket.AF_INET,socket.SOCK_STREAM)

phone.bind(('127.0.0.1',8080))

phone.listen(5)

conn, client_addr = phone.accept()
from_client_data1 = conn.recv(1024)
print(from_client_data1)
from_client_data2 = conn.recv(1024)
print(from_client_data2)
from_client_data3 = conn.recv(1024)
print(from_client_data3)
conn.close()
phone.close()

# recv空字符串: 对方客户端关闭了,且服务端的缓冲区没有数据了,我再recv取到空bytes.

高阶版黏包解决方案

服务端:

import socket
import subprocess
import struct
import json

phone = socket.socket()
phone.bind(('127.0.0.1',8897))

phone.listen(3)
print("等待接入")
while 1:
    conn, addr = phone.accept()
    print(conn, addr)
    try:
        while 1:
            from_client_data = conn.recv(1024)
            if from_client_data.decode('utf-8').upper() == 'Q':
                print('对方中断链接')
                break
            obj = subprocess.Popen(from_client_data.decode('utf-8'),
                                   shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   )

            to_client_data = obj.stdout.read() + obj.stderr.read()
            total_size = len(to_client_data)
            dic = {'filename':'text1','MD5':120045318563413485631,'total_size':total_size}
            head1 = json.dumps(dic).encode('utf-8')

            len_head1 = len(head1)
            head_bytes = struct.pack('i',len_head1)
            conn.send(head_bytes)
            conn.send(head1)
            conn.send(to_client_data)
    except ConnectionError:
        print('对方中断网络链接')
        break
    conn.close()
phone.close()

客户端:

import socket
import struct
import json
phone = socket.socket()

phone.connect(('127.0.0.1',8897))
while 1:
    to_server_data = input('请输入内容')
    phone.send(to_server_data.encode('utf-8'))
    if to_server_data.upper() == "Q":
        print('主动退出')
        break
    if not to_server_data.strip():
        continue
    head = phone.recv(4)
    num = struct.unpack('i',head)[0]
    dic_head = phone.recv(num).decode('utf-8')
    dic = json.loads(dic_head)
    s = b''
    while len(s) < dic['total_size']:
        from_server_data = phone.recv(1024)
        s += from_server_data
    print(s.decode('gbk'))
phone.close()

基于UDP的socket通信

服务端:

import socket
server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# 基于网络的UDP协议的socket
server.bind(('192.168.14.198',9000))

while 1:

    from_client_data = server.recvfrom(1024)  # 阻塞,等待客户来消息
    print(f'\033[1;35;0m来自客户端{from_client_data[1]}: {from_client_data[0].decode("utf-8")} \033[0m')
    to_client_data = input('>>>').strip()
    server.sendto(to_client_data.encode('utf-8'),from_client_data[1])


# 1. 基于udp协议的socket无须建立管道,先开启服务端或者客户端都行.
# 2. 基于udp协议的socket接收一个消息,与发送一个消息都是无连接的.
# 3. 只要拿到我的ip地址和端口就都可以给我发消息,我按照顺序接收消息.

客户端:

import socket
server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# 基于网络的UDP协议的socket
server.bind(('192.168.14.198',9000))

while 1:

    from_client_data = server.recvfrom(1024)  # 阻塞,等待客户来消息
    print(f'\033[1;35;0m来自客户端{from_client_data[1]}: {from_client_data[0].decode("utf-8")} \033[0m')
    to_client_data = input('>>>').strip()
    server.sendto(to_client_data.encode('utf-8'),from_client_data[1])


# 1. 基于udp协议的socket无须建立管道,先开启服务端或者客户端都行.
# 2. 基于udp协议的socket接收一个消息,与发送一个消息都是无连接的.
# 3. 只要拿到我的ip地址和端口就都可以给我发消息,我按照顺序接收消息.

标签:socket,data,黏包,phone,client,recv,conn
来源: https://www.cnblogs.com/lifangzheng/p/11366039.html