python太方便了.许多有趣的功能他已经全部集成进去,让你的实现非常方便.在实际生活中,socket并发连接是很常见的现象,用其它语言相对麻烦一些,而用python,一切都变得非常简单.
下面是一个简单的实现.
server:
import SocketServer
from SocketServer import StreamRequestHandler
#class MyHandler(SocketServer.BaseRequestHandler):
class MyHandler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print 'got connection from ',addr
self.wfile.write('thx for your connection')
while 1:
data_received = self.request.recv(1024)
if not data_received: break
print data_received
self.request.send(data_received)
my_server = SocketServer.ThreadingTCPServer(("192.168.1.103",8000),MyHandler)
my_server.serve_forever()
|
client:
# Echo client program
import socket
HOST = '192.168.1.103' # The remote host
PORT = 8000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
client_msg = raw_input()
if cmp(client_msg,'exit') == 0:
break
s.send(client_msg)
data = s.recv(1024)
print 'Received', repr(data)
s.close()
|
当然,我们看到,还是通过多线程来实现并发连接的问题.