python网络编程之 创建一个socketserverTCP服务器

 1 #encoding=utf-8
 2 #创建一个socketserverTCP服务器
 3 #高级模块,简化客户和服务器的实现
 4 from SocketServer import (TCPServer as TCP,StreamRequestHandler as SRH)
 5 from time import ctime
 6 
 7 host = ''
 8 port = 21567
 9 addr = (host,port)
10 
11 #从 SocketServer 的 StreamRequestHandler 类中派生出一个子类
12 class MyRequestHandler(ARH):
13   def handel(self):
14     print 'connected from ',self.client_address
15     self.wfile.write('[%s] %s ' % (ctime(),self.rfile.readline()))
16   #用 readline()函数得到客户消息,用 write()函数把字符串发给客户。
17 
18 tcpServ = TCP(addr,MyRequestHandler)
19 print 'waiting for connection'
20 tcpServ.serve_forever()


 1 #encoding=utf-8
 2 # 是一个时间戳 TCP 客户端,它知道如何与 SocketServer 里 StreamRequestHandler 对象进行
 3 # 通讯。
 4 from socket import *
 5 
 6 host = 'localhost'
 7 port = 21567
 8 bufsiz = 1024
 9 addr = (host,port)
10 
11 while True:
12     tcpClientSock = socket(AF_INET,SOCK_STREAM)
13     tcpClientSock.connect(addr)
14     data = raw_input('>')
15     if not data:
16         break
17     tcpClientSock.send('%s\r\n' % data)
18 #     我们可以用 readline()函数得到客户消息,用 write()函数把字
19 # 符串发给客户。
20 # 为了保持一致性,我们要在客户与服务器两端的代码里都加上回车与换行。实际上,你在代码
21 # 中看不到这个,因为,我们重用了客户传过来的回车与换行。
22     data = tcpClientSock.recv(bufsiz)
23     if not data:
24         break
25     print data.strip()
26 
27 tcpClientSock.close()