今天看了下python的socket,想实现下两台电脑的聊天功能(觉得这样好像自己写出个简易版QQ没问题了),于是动手开始实现。
首先是服务器端:
from socket import *
from time import ctime
HOST=''
PORT=80 #端口号,服务器与客户端要一致
BUFSIZ=1024 #传送数据的缓冲区大小,随意设置
ADDR=(HOST,PORT) #链接地址
tcpSS=socket(AF_INET,SOCK_STREAM)
tcpSS.bind(ADDR)
tcpSS.listen(5)
while True:
print "waiting for connection.."
tcpCS,addr=tcpSS.accept()
print "...connected from:",addr
while True:
data=tcpCS.recv(BUFSIZ)
if not data:
exit(0)
print "[%s] \n%s"%(ctime() ,data)
data =raw_input('[%s]\n'%ctime())
tcpCS.send("%s"%data)
tcpCS.close()
tcpSS.close()
接着是客户端:
from socket import *
from time import ctime
HOST='192.168.1.104'
PORT=80
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpCS=socket(AF_INET,SOCK_STREAM)
tcpCS.connect(ADDR)
while True:
data=raw_input('[%s]\n'%ctime())
if not data:
break
tcpCS.send(data)
data=tcpCS.recv(BUFSIZ)
if not data:
break
print "[%s]\n%s"%(ctime(),data)
tcpCS.close()
主要就是数据接收和传送,没什么特别的地方。
简单实现了客户端与服务器的一来一往的对话,并带有时间标签。只是为了玩一下。