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)

 

posted @ 2019-11-12 21:24  zh_小猿  阅读(201)  评论(0编辑  收藏  举报