HOST = ''
PORT = 5555
BUFSIZ = 128
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.settimeout(None)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
input = [tcpSerSock, sys.stdin] #input是一个列表,初始有欢迎套接字以及标准输入
while True:
# 开始监听客户端
print ('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print ('...connected from:',addr)
input.append(tcpCliSock) #将服务套接字加入到input列表中
# 处理发送和接收数据
while True:
senddata=''
recvmsg=''
readyInput,readyOutput,readyException = select.select(input,[],[]) #从input中选择,轮流处理client的请求连接(tcpSerSock),client发送来的消息(tcpCliSock),及服务器端的发送消息(stdin)
for indata in readyInput:
#【接收】
if indata==tcpCliSock: #处理client发送来的消息
recvmsg = tcpCliSock.recv(BUFSIZ)
if recvmsg=='88' or recvmsg=='': # 服务端主动断开 or 客户端主动断开
input.remove(tcpCliSock)
break # 退出for
print("[recv]:%s" %(recvmsg.decode()) )
# 此处增加接收处理逻辑
recv_handler(tcpCliSock,recvmsg)
else: #【发送】#处理服务器端的发送消息
senddata = raw_input('>>')
if senddata=='88':
tcpCliSock.send('%s' %(senddata))
input.remove(tcpCliSock)
break
try:
# 此处增加发送逻辑
print('[input=]',senddata)
tcpCliSock.send("rep:"+senddata)
except Exception as e:
print('[rep]',e)
if senddata=='88' or recvmsg=='': # 服务端主动断开 or 客户端主动断开
break # 退出&&关闭客户端
# second while end 关闭已连接客户端
tcpCliSock.close()
break # 退出socket服务端程序
# first while end
tcpSerSock.close()
print('.'*50)
python 服务端程序
最新推荐文章于 2022-05-11 23:44:01 发布