模块:socketserver
tcp协议:
服务端:
import socketserver
class MyRequestHandle(socketserver.BaseRequestHandler):
def handle(self):
# print(self.request) #如果tcp协议,self.request = conn
print(self.client_address)
while True:
try:
msg = self.request.recv(1024)
if msg == 0:break
print(msg.decode('utf8'))
self.request.send(msg.upper())
except Exception:
break
self.request.close()
#服务端应该做的两件事
#第一件事:循环的从半连接池中取出链接请求与其建立双向链接,拿到链接对象
s = socketserver.ThreadingTCPServer(('127.0.0.1',8081),MyRequestHandle)
s.serve_forever()
#等同于:
# while True:
# conn,client_addr = server.accept() 每建立一个链接都会启动一个线程
#启动一个线程(conn,client_addr)
#第二件事:拿到链接对象,与其进行通信循环===》handle
客户端:
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #流式协议--> tcp协议
client.connect(('127.0.0.1',8081)) #进行3次握手
while True:
msg = input('输入要发送的消息:').strip()
if len(msg) == 0:continue #解决输入空格的bug
client.send(msg.encode('utf8')) #编码以二进制的形式发送
res = client.recv(1024)
print(res.decode('utf8'))
client.close()
udp协议:
服务端:
import socketserver
class MyRequestHanlde(socketserver.BaseRequestHandler):
def handle(self):
client_data = self.request[0]
print('客户端发来的数据%s'%client_data) #元组中第一个内容
server = self.request[1] #套接字对象
client_address = self.client_address #ip+接口
server.sendto(client_data.upper(),client_address) #转成大写形式返回
s = socketserver.ThreadingUDPServer(('127.0.0.1',8090),MyRequestHanlde)
s.serve_forever()
#相当于只负责循环的收
用户端:
from socket import *
slient = socket(AF_INET,SOCK_DGRAM)
while True:
msg = input('>>>>:').strip()
slient.sendto(msg.encode('utf8'),('127.0.0.1',8090))
res = slient.recvfrom(1024)
print(res)
slient.close()
标签:socket,socketserver,self,request,client,msg,多线程 From: https://www.cnblogs.com/whxx/p/17267155.html