zoukankan      html  css  js  c++  java
  • socketserver的使用

    1、基于tcp

    服务端:

    import socketserver
    
    # 通信循环
    class MytcpHandler(socketserver.BaseRequestHandler):
        def handle(self):
            while True:
                try:
                    data = self.request.recv(1024)  # 把conn封装到self.request中
                    if not data: break  # 针对linux系统
                    self.request.send(data.upper())  # 注意:收发都是以bytes为单位
                except ConnectionResetError:
                    break
            self.request.close()
    
    
    if __name__ == '__main__':
        #连接循环
        server=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MytcpHandler)
        server.serve_forever()
    
        print(server.server_address)
        print(server.RequestHandlerClass)
        print(server.socket)

    客户端:

    import socket
    
    client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    client.connect(('127.0.0.1',8080))
    
    while True:
        msg=input('>>: ').strip()
        client.send(msg.encode('utf-8'))
        data=client.recv(1024)
        print(data.decode('utf-8'))
    
    client.close()

    2、基于udp

    服务端:

    import socketserver
    
    # 通信循环
    class MyUDPHandler(socketserver.BaseRequestHandler):
        def handle(self):
            # print(self.request)
            res=self.request[0]  #self.request相当于一个元组(客户端发过来的消息,专门用来给客户端回消息的套接字对象)
            print('客户端发来的数据:',res)
    
            self.request[1].sendto(res.upper(),self.client_address)
    
    
    if __name__ == '__main__':
        #连接循环
        server=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyUDPHandler)
        server.serve_forever()

    客户端:

    import socket
    import os
    
    client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    
    while True:
        msg='%s hello' %os.getpid()
        client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    
        res,server_addr=client.recvfrom(1024)
        print(res)
  • 相关阅读:
    BP反向传播
    神经网络基本概念理解
    梯度下降算法理解(梯度的含义)
    ResNet
    残差是什么?拟合是什么?
    Perceptual Losses for Real-Time Style Transfer and Super-Resolution 论文理解
    java动手动脑之多态
    java 动手动脑之父子继承
    java动手动脑
    java验证课上代码
  • 原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/11845404.html
Copyright © 2011-2022 走看看