UDP协议的socket
pdu协议:不可靠,相对来说不安全的协议,面向数据报(无连接)的协议,效率高,速度快.
# client
import socket
udp_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 基于网络,udp协议的socket
while 1:
to_server_data = input('>>>').strip()
udp_client.sendto(to_server_data.encode('utf-8'),('127.0.0.1', 9000))
from_server_data = udp_client.recvfrom(1024)
print(f'来自{from_server_data[1]}的消息:{from_server_data[0].decode("utf-8")}')
# server
import socket
udp_server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 基于网络,udp协议的socket
udp_server.bind(('127.0.0.1', 9000))
while 1:
from_client_data = udp_server.recvfrom(1024)
print(f'来自{from_client_data[1]}的消息:{from_client_data[0].decode("utf-8")}')
to_client_data = input('>>>').strip()
udp_server.sendto(to_client_data.encode('utf-8'),from_client_data[1])
# udp不会产生粘包的现象 并且默认支持一对多(串行)
网络并发
# server
import socketserver
class MyServer(socketserver.BaseRequestHandler): # 继承的类固定的
def handle(self): # 必须是这个handle名字.
while 1:
from_client_data = self.request.recv(1024).decode('utf-8') # self.request == conn管道
print(from_client_data)
to_client_data = input('>>>').strip()
self.request.send(to_client_data.encode('utf-8'))
if __name__ == '__main__':
ip_port = ('127.0.0.1',8848)
server = socketserver.ThreadingTCPServer(ip_port,MyServer)
# server.allow_reuse_address = True
# print(socketserver.ThreadingTCPServer.mro())
# [ThreadingTCPServer, ThreadingMixIn,TCPServer, BaseServer]
server.serve_forever()
# client
import socket
# 1. 创建socket对象(买手机)
phone = socket.socket() # 可以默认不写
# 连接服务器ip地址与端口
phone.connect(('127.0.0.1', 8848))
# 发消息
while 1:
content = input('>>>').strip()
phone.send(f'MC阿强:{content}'.encode('utf-8'))
# 接收消息
from_server_data = phone.recv(1024) # 夯住,等待服务端的数据传过来
print(f'来自服务端消息:{from_server_data.decode("utf-8")}')
# 关机
phone.close()