快捷搜索:  汽车  科技

websocket和udp直接通信(基于socketserver实现并发tcpudp)

websocket和udp直接通信(基于socketserver实现并发tcpudp)

1.基于socketserver实现并发-tcp


  1. #服务端
  2. import socketserver
  3. class MyHandler(socketserver.BaseRequesthandler):
  4. def handle(self):
  5. #print(self.client_address) #客户端地址
  6. #print(self.request) ##self.request=conn 套接字对象
  7. while True:
  8. try:
  9. data = self.request.recv(1024)
  10. if len(data) == 0: break
  11. print()
  12. self.request.send(data.upper())
  13. except ConnectionResetError:
  14. break
  15. if __name__ == '__main__':
  16. s = socketserver.ThreadingTCPServer(('127.0.0.1' 8080) MyHandler bind_and_activate=True)
  17. s.serve_forever() #代表连接循环
  18. #循环建立连接,每建立一个连接就会启动一个线程 调用MyHandler类产生一个对象,
  19. #该对象下面的handle方法,专门与刚刚建立好的连接做通信循环

  1. #客户端
  2. import socket
  3. phone=socket.socket(socket.AF_INET socket.SOCK_STREAM)
  4. phone.connect(('127.0.0.1' 8080))
  5. while True:
  6. msg=input(">>>>>>>>>>>>>").strip()
  7. if len(msg)==0:continue
  8. phone.send(msg.encode('utf-8'))
  9. data=phone.recv(1024)
  10. print(data)
  11. phone.close()

1.基于socketserver实现并发-ucp


  1. #服务端
  2. import socketserver
  3. class MyHandeler(socketserver.BaseRequestHandler):
  4. def handle(self):
  5. data = self.request[0] #request是个元组,元组的第一个是数据,第二个是一个套接字对象
  6. print('消息' data)
  7. self.request[1].sendto(data.upper() self.client_address) #self.request[1] 是套接字对象
  8. if __name__ == '__main__':
  9. s = socketserver.ThreadingUDPServer(('127.0.0.1' 8080) MyHandeler)
  10. s.serve_forever()
  11. #客户端
  12. import socket
  13. client=socket.socket(socket.AF_INET socket.SOCK_DGRAM)
  14. while True:
  15. msg=input('>>>>>>>').strip()
  16. #msg='111111111111'
  17. client.sendto(msg.encode('utf-8') ('127.0.0.1' 8080))
  18. data server_addr=client.recvfrom(1024)
  19. print(data)
  20. client.close()

websocket和udp直接通信(基于socketserver实现并发tcpudp)(1)

猜您喜欢: