根据核心编程里的代码,自己改编的socket聊天工具
####client####
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('input your words:')
if not data:
break
tcpCliSock.send('%s\r\n' %data)
data='......['+str(tcpCliSock.getsockname())+tcpCliSock.recv(BUFSIZ)
if not data:
break
print data.strip()
tcpCliSock.close()
####server####
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 '...connect form...',self.client_address
print '......[%s%s]:%s' %(self.client_address,ctime(),self.rfile.readline())
inp=raw_input('input you words:')
self.wfile.write('%s:]%s' %(ctime(),inp))
tcpServ=TCP(ADDR,MyRequestHandler)
print 'waitint for connection...'
tcpServ.serve_forever()