服务端等待客户端连接并接收客户端信息,然后将客户端信息加上时间戳返回给客户端, 当客户端输入空消息时,连接中断,服务端继续坚挺其他连接。
服务端代码:
from socket import *
from time import ctime
HOST = '' #监听所有地址
PORT = 21560
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(family=AF_INET, type=SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting...')
tcpCliSock, addr = tcpSerSock.accept()
print '...connect from:', addr
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print data
tcpCliSock.send('[%s] %s' % (ctime(), data))
tcpCliSock.close()
tcpSerSock.close()
客户端代码:
from socket import *
HOST = 'localhost'
PORT = 21560
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = raw_input('> ')
print type(data)
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print data
tcpCliSock.close()
2024 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123