作者:mobiledu2502880051 | 来源:互联网 | 2023-06-20 13:35
本质原因:不知道要接收多大的数据tcp会黏包但是不会丢包#因为组合(发送端缓冲区(tcp特有)满)和拆分(多个包接收)数据包udp不会黏包,但是会丢包#sendto函数最大能发送数据的
本质原因:不知道要接收多大的数据
tcp会黏包但是不会丢包 #因为组合(发送端缓冲区(tcp特有)满)和拆分(多个包接收)数据包
udp不会黏包,但是会丢包 #sendto函数最大能发送数据的长度为:65535-ip头(20)-UDP头(8)=65507字节
超长会报错并丢包
tcp_sever:
import socket
sk = socket.socket()
sk.bind(('127.0.0.1',8090))
sk.listen()
conn, addr = sk.accept()
while True:
cmd = input('>>>')
conn.send(cmd.encode('gbk'))
ret = conn.recv(1024).decode('utf-8')
print(ret)
conn.close()
sk.close()
tcp_client:
import socket
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1',8090))
while 1:
cmd = sk.recv(1024).decode('gbk')
ret = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out = 'stdout:' + (ret.stdout.read().decode('gbk'))
std_err = 'stderr:' + (ret.stderr.read().decode('gbk'))
sk.send(std_out.encode('utf-8'))
sk.send(std_err.encode('utf-8'))
sk.close()
udp_sever:
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',8090))
msg,addr = sk.recvfrom(1024)
while True:
cmd = input('>>>')
if cmd == 'q':
break
sk.sendto(cmd.encode('gbk'),addr)
ret = sk.recv(1024).decode('utf-8')
print(ret)
sk.close()
udp_client:
import socket
import subprocess
sk = socket.socket(type=socket.SOCK_DGRAM)
addr = ('127.0.0.1',8090)
while 1:
sk.sendto('吃了么'.encode('utf-8'),addr)
cmd,addr = sk.recvfrom(1024)
ret = subprocess.Popen(cmd.decode('gbk'), shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
std_out = 'stdout:' + (ret.stdout.read().decode('gbk'))
std_err = 'stderr:' + (ret.stderr.read().decode('gbk'))
sk.sendto(std_out.encode('utf-8'),addr)
sk.sendto(std_err.encode('utf-8'),addr)
sk.close()