基于socketserver模块并发套接字

1、基于tcp协议

服务端:

import socketserver
class MyHandler(socketserver .BaseRequestHandler ):
def handle(self): #通信循环
while True :
try:
data = self.request .recv(1024) #request表示建立的链接
if len(data)== 0:break
self.request .send(data.upper())
except ConnectionResetError :
break
if __name__=='__main__' :
s= socketserver .ThreadingTCPServer (('127.0.0.1',8080),MyHandler ,bind_and_activate= True )
s.serve_forever()
# 链接循环,每建立一个链接就会启动一个线程,并调用Myhanlder类产生一个对象,调用对象下的handle方法
# 与刚刚建立好的链接做通讯循环

客户端:
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080)) # 指定服务端ip和端口

while True:
msg=input('>>: ').strip() #msg=''
#msg = 'client22222' # msg=''
if len(msg) == 0:continue
phone.send(msg.encode('utf-8'))
data=phone.recv(1024)
print(data)
phone.close()

2、基于udp协议
#服务端
class Myhandler(socketserver .BaseRequestHandler ):
def handler(self):
#print(self.client_address ) #客户端IP和端口
# 套接字对象 (b'gg', <socket.socket fd=344, family=AddressFamily.AF_INET, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('127.0.0.1', 8080)>)
#print(self.request)
data = self.request [0] #对应着客户端发来的信息
print('客户消息',data)
self.request [1].sendto(data.upper(),self.client_address )
if __name__ == '__main__':
s= socketserver .ThreadingUDPServer (('127.0.0.1',8080),Myhandler )
s.serve_forever()

客户端:
import socket
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #数据报协议-》udp
while True:
msg=input('>>: ').strip() #msg=''
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data,server_addr=client.recvfrom(1024)
print(data)

client.close()





























































posted @ 2018-07-11 14:26  朝朝哥  阅读(121)  评论(0编辑  收藏  举报