python多进程、多线程服务器和客户端的简单实现

使用了多进程的服务器:

from SocketServer import TCPServer, ForkingMixIn, ThreadingMixIn, StreamRequestHandler

class Server(ThreadingMixIn, TCPServer):
    pass

class Handler(StreamRequestHandler):
    def handle(self):
        addr = self.request.getpeername()
        print('Got connection from', addr)
        self.wfile.write('Thank you for connecting')

server = Server(('', 1234), Handler)
server.serve_forever()

 

使用了多线程的服务器:

from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler

class Server(ThreadingMixIn, TCPServer):
    pass

class Handler(StreamRequestHandler):
    def handle(self):
        addr = self.request.getpeername()
        print 'Got connection from', addr
        self.wfile.write('Thank you for connecting')

server = Server(('', 1234), Handler)
server.serve_forever()

 

客户端:

import socket

s = socket.socket()
host = socket.gethostname()
port = 1234

s.connect((host, port))
print(s.recv(1024))

 

posted on 2016-12-07 15:09  lakeone  阅读(398)  评论(0编辑  收藏  举报

导航