socketserver 实现并发

server.py

# socketserver 实现并发
import socketserver
class MyServer(socketserver.BaseRequestHandler):    # 继承socketserver.BaseRequestHandler这个类
    def handle(self):      # 必须定义handle方法
        print('conn is:', self.request)     # self.request双向连接信息
        print('addr is', self.client_address)   # self.client_address客户端地址及端口

        while True:     # 通信循环
            try:    # 如果客户端强制退出,会报错,则需要做异常处理
                # 收消息
                data = self.request.recv(1024)
                if not data:break   # 如果收到为空会卡住,则跳出循环
                print('客户端收到的消息是', data)

                # 发消息
                self.request.sendall(data.upper())  # 将客户端发的信息大写后发给客户端,使用sendall相当于循环使用send直到把所有数据都发送完毕

            except Exception as e:
                print(e)
                break

if __name__ == '__main__':
    s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyServer)  # 开启多线程tcp服务
    s.serve_forever()   # 运行服务端

client.py

from socket import *

ip_port = ('127.0.0.1', 8080)
back_log = 5
buff_size = 1024

tcp_client = socket(AF_INET, SOCK_STREAM)
tcp_client.connect(ip_port)

while True:
    msg = input('>>:').strip()
    if not msg: continue
    if msg == 'quit': break

    tcp_client.send(msg.encode('utf-8'))

    data = tcp_client.recv(buff_size)
    print('收到服务端发来的消息:', data.decode('utf-8'))

tcp_client.close()

 udp服务端(不常用)

import socketserver

class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        print(self.request)
        print('收到客户端的消息是',self.request[0])
        self.request[1].sendto(self.request[0].upper(),self.client_address)


if __name__ == '__main__':
    s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyServer) #多线程
    s.serve_forever()

 

posted @ 2018-08-15 23:43  四十不惑的编程之路  阅读(138)  评论(0编辑  收藏  举报