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))