应用:模拟QQ聊天
客户端参考代码
from socket import *
tcpClientSocket = socket(AF_INET, SOCK_STREAM)
serAddr = ('192.168.1.102', 7788)
tcpClientSocket.connect(serAddr)
while True:
sendData = raw_input("send:")
if len(sendData)>0:
tcpClientSocket.send(sendData)
else:
break
recvData = tcpClientSocket.recv(1024)
print 'recv:',recvData
tcpClientSocket.close()
服务器端参考代码
from socket import *
tcpSerSocket = socket(AF_INET, SOCK_STREAM)
address = ('', 7788)
tcpSerSocket.bind(address)
tcpSerSocket.listen(5)
while True:
newSocket, clientAddr = tcpSerSocket.accept()
while True:
recvData = newSocket.recv(1024)
if len(recvData)>0:
print 'recv:',recvData
else:
break
sendData = raw_input("send:")
newSocket.send(sendData)
newSocket.close()
tcpSerSocket.close()