代码改变世界

python之多并发socket(zz)

2017-09-22 12:33  很大很老实  阅读(511)  评论(0编辑  收藏  举报

本文转载自:http://www.cnblogs.com/bainianminguo/p/7337210.html

先看socket多并发的服务端的代码,这里是用多线程实现的多并发socketserver

import socketserver

# socketserver有四个基本的类,后两个不常用,这4个类处理并发请求都是同步的,他们其实不是多线程的,
# 他们只是把socke封装了一下,加了一些方法,这里还没有实现多并发和多线程
# 这些方法不适用每个请求都耗费长时间才能完成


# socketserver.TCPServer
# socketserver.UDPServer
# socketserver.UnixStreamServer
# socketserver.UnixDatagramServer
# socketserver.ForkingMixIn
# socketserver.ThreadingMixIn

# ========================================================================================================
# 我们真正要用的下面这4个方法
# 多进程的socketserver
# socketserver.ForkingTCPServer
# socketserver.ForkingUDPServer

# 多进程的socketserver
# socketserver.ThreadingTCPServer
# socketserver.ThreadingUDPServer


# ========================================================================================================
class MyTcpServerClass(socketserver.BaseRequestHandler):
    def handle(self):
        print("waiting for new connect:")
        print("new client :",self.client_address)
        while True:
            try:
                data=self.request.recv(1024)
                print("the client:",self.client_address,str(data,encoding='utf-8'))
            except Exception:
                print("the client [%s] is unconnected!"%(self.client_address[1]))
                self.request.close()
                break



if __name__=='__main__':
    ipbind=('127.0.0.1',2345)
    server=socketserver.ThreadingTCPServer(ipbind,MyTcpServerClass)
    server.serve_forever()

然后看下客户端的代码:

import socket

ipbind=('127.0.0.1',2345)

c=socket.socket()
c.connect(ipbind)

while True:
    c_input=input("客户端:")
    c.send(bytes(c_input,encoding='utf-8'))
    s_send=c.recv(1024)
    print("服务端:",str(s_send,encoding='utf-8'))