python实现的高并发tcp服务器,相当于网络调试助手

# 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()
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值