# coding=utf-8
import socket
import threading
import sys
import os
import time
import datetime
class ViewLog():
def __init__(self):
pass
def receive(self,client,clientList):
while True:
try:
msg = client.recv(1024)
print(datetime.datetime.today())
print('收到客户端消息:' + msg)
client.send('{"msgType":111,"devId":"BAT0000000001","result":1,"txnNo":123456789}')
except Exception as err:
print(err)
client.close()
break
if not msg:
print('客户端主动断开')
client.close()
break
def send(self,clientList):
while True:
print('请在下面输入指令:')
inp = raw_input()
inp = str(inp)
print('您输入的指令是: '+inp)
removeList = []
for inx , client in enumerate(clientList) :
try :
if inp == 'a' : #当控制台输入a时
client.close()
removeList.append(client)
elif inp == 'b' : #当控制台输入b时
client.send('{"msgType":210,"devId":"BAT0000000001","paramList":[{"id":"01303001"},{"id":01304001"}],"txnNo":"123456789","time":12345678}')
except Exception as err :
removeList.append(client)
for remove0 in removeList :
clientList.remove(remove0)
#print(clientList)
def viewLog(self):
print("服务已启动")
clientList = []
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
mySocket.bind(('', 9000)) # 设置IP和端口 bind绑定该端口
mySocket.listen(2) # 监听
threading.Thread(target=ViewLog().send, args=(clientList,)).start() # 创建一个向客户端发送数据的线程
while True:
client, address = mySocket.accept()
print('新客户端已连接 ' + str(address[0]) + ' ' + str(address[1]))
threading.Thread(target=ViewLog().receive, args=(client,clientList)).start() # 创建一个接受客户端数据的线程
clientList.append(client)
mySocket.close()
if '__main__' == __name__:
ViewLog().viewLog()
python实现的高并发tcp服务器,相当于网络调试助手
最新推荐文章于 2022-07-11 07:38:00 发布