基于TCP
服务端
import socketserver
class MyRequestHandle(socketserver.BaseRequestHandler):
def handle(self):
# 如果tcp协议,self.request=>conn
print(self.client_address)
while True:
try:
msg = self.request.recv(1024)
if len(msg) == 0: break
self.request.send(msg.upper())
except Exception:
break
self.request.close()
# 服务端应该做两件事
# 第一件事:循环地从半连接池中取出链接请求与其建立双向链接,拿到链接对象
s=socketserver.ThreadingTCPServer(('127.0.0.1',8889),MyRequestHandle)
s.serve_forever()
# 等同于
# while True:
# conn,client_addr=server.accept()
# 启动一个线程(conn,client_addr)
# 第二件事:拿到链接对象,与其进行通信循环===>handle
客户端
from socket import *
client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8889))
while True:
msg=input('请输入命令>>:').strip()
if len(msg) == 0:continue
client.send(msg.encode('utf-8'))
res=client.recv(1024)
print(res.decode('utf-8'))
基于UDP
服务端
import socketserver
class MyRequestHanlde(socketserver.BaseRequestHandler):
def handle(self):
client_data=self.request[0]
server=self.request[1]
client_address=self.client_address
print('客户端发来的数据%s' %client_data)
server.sendto(client_data.upper(),client_address)
s=socketserver.ThreadingUDPServer(("127.0.0.1",8888),MyRequestHanlde)
s.serve_forever()
# 相当于:只负责循环地收
# while True:
# data,client_addr=server.recvfrom(1024)
# 启动一个线程处理后续的事情(data,client_addr)
客户端
import socket
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 流式协议=》tcp协议
while True:
msg=input('>>>: ').strip()
client.sendto(msg.encode('utf-8'),('115.29.65.16',8888))
res=client.recvfrom(1024)
print(res)
client.close()