SocketServer是python网络编程的一个高级模块,封装了一些底层的基本方法,用SocketServer改写上一篇中的例子,服务端的程序如下:
'''
Created on 2012-3-9
@author: Administrator
'''
#!/usr/bin/env python
from SocketServer import (TCPServer as TCP,StreamRequestHandler as SRH)
from time import ctime
HOST=''
PORT=21567
ADDR=(HOST,PORT)
class MyRequestHandler(SRH):
def handle(self):
print '...connected from:',self.client_address
self.wfile.write('[%s] %s' %(ctime(),self.rfile.readline()))
tcpServ = TCP(ADDR,MyRequestHandler)
print 'waiting for connection...'
tcpServ.serve_forever()
是不是简单很多呢,主要注意类
MyRequestHandler是StreamRequestHandler的子类,handle方法是父类的方法,在这里复写并打印。
客户端的程序没什么变化:
'''
Created on 2012-3-9
@author: Administrator
'''
#!/usr/bin/env python
from socket import *
HOST='localhost'
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)
while True:
tcpCliSock=socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
data=raw_input('>')
if not data:
break
tcpCliSock.send('%s \r\n' % data)
data=tcpCliSock.recv(BUFSIZ)
if not data:
break
print data.strip()
tcpCliSock.close()