基于udp协议的套接字通信

服务端:

import socket

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8080)) while True:
res,client_addr=server.recvfrom(1024)
# print(data)
server.sendto(res.upper(),client_addr)

客户端:

import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

while True:
msg=input('>> ').strip()
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080)) res,server_addr=client.recvfrom(1024)
print(res)

udp协议不会粘包:

服务端:

import socket

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8080)) res1,client_addr=server.recvfrom(1024) #b'hello'
print(res1) res2,client_addr=server.recvfrom(1024) #b'wolrd'
print(res2) res3,client_addr=server.recvfrom(1024) #b'oldboy123456'
print(res3)

客户端:

import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

client.sendto('hello'.encode('utf-8'),('127.0.0.1',8080))
client.sendto('wolrd'.encode('utf-8'),('127.0.0.1',8080))
client.sendto('oldboy123456'.encode('utf-8'),('127.0.0.1',8080))

打印结果:

b'hello'
b'wolrd'
b'oldboy123456'

udp是无链接的,先启动哪一端都不会报错

上一篇:WebService方法返回json


下一篇:网络编程基础:粘包现象、基于UDP协议的套接字