基于UDP协议的套接字
user datagram protocal 数据报协议
无双向通道、自带报头、类似发短信、不会粘包
不可靠:数据发送时,丢就丢了
UDP socket:
服务端:
import socket
server = socket.socket(type=socket.SOCK_DGRAM) # UDP协议
server.bind(('127.0.0.1', 8080))
# 无半连接池概念,不需要listen
# 无双向通道,直接通信循环
while True:
data, addr = server.recvfrom(1024) # 直接接受客户端消息
print(data)
print(addr)
server.sendto(data.decode('utf-8').upper().enco
客户端:
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
# 无双向通道,不需要连接,直接进入通信循环
server_address = ('127.0.0.1', 8080)
while True:
data = input('>>>').strip()
client.sendto(data.encode('utf-8'), server_address)
server_data, server_addr = client.recvfrom(1024)
print(server_data)
print(server_addr)
应用:简单版qq
服务端:
import socket
server = socket.socket(type=socket.SOCK_DGRAM)
server.bind(('127.0.0.1', 8080))
while True:
data, addr = server.recvfrom(1024)
print('你收到了一条消息:{0}'.format(data.decode('utf-8')))
msg = input('回信:>>>').strip()
server.sendto(msg.encode('utf-8'), addr)
客户端:
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1', 8080,)
while True:
msg = input('输入你发送的消息>>>').strip()
client.sendto(msg.encode('utf-8'), server_address)
data, addr = client.recvfrom(1024)
print('服务器回信:{0}'.format(data.decode('utf-8')))
socketserver模块
创建基于TCP协议的套接字:
服务端
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
print('服务端的handler')
while True:
data = self.request.recv(1024)
print(self.client_address)
print(data)
self.request.send(data.upper())
if __name__ == '__main__':
# 只要有客户端连接,就会自动交给handler类中的handle处理
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8000), MyServer) #创建一个基于TCP的对象
server.serve_forever() # 启动该服务对象
客户端:
import socket
client = socket.socket()
client.connect(('127.0.0.1', 8000))
while True:
msg = input('>>>').strip()
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print('客户端收到的数据',data)
创建基于UDP的套接字
服务端:
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
# print('来啦 老弟')
while True:
data,sock = self.request
print(self.client_address) # 客户端地址
print(data.decode('utf-8'))
sock.sendto(data.upper(),self.client_address)
if __name__ == '__main__':
"""只要有客户端连接 会自动交给自定义类中的handle方法去处理"""
server = socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyServer) # 创建一个基于TCP的对象
server.serve_forever() # 启动该服务对象
客户端:
import socket
import time
client = socket.socket(type=socket.SOCK_DGRAM)
server_address = ('127.0.0.1',8080)
while True:
client.sendto(b'hello',server_address)
data,addr = client.recvfrom(1024)
print(data.decode('utf-8'),addr)
time.sleep(1)