python可控制的tcp服务器

  1. import threading,socket
  2. class Debug():
  3.     dbswtch = 1
  4.     def out(dbstr):
  5.         if(Debug.dbswtch == 1):
  6.             print(dbstr)
  7.             
  8. class Cmd(threading.Thread):
  9.     def __init__(self):
  10.         threading.Thread.__init__(selfNone)
  11.     def menu(self):
  12.         print("you can input:")
  13.         print("   debug on")
  14.         print("   debug off")
  15.         print("   see debug")
  16.         print("   exit")
  17.     def run(self):
  18.         self.menu()
  19.         while(True):
  20.             cmd = input()
  21.             if(cmd == "debug on"):
  22.                 Debug.dbswtch = 1
  23.             elif(cmd == "debug off"):
  24.                 Debug.dbswtch = 0
  25.             elif(cmd == "see debug"):
  26.                 if(1 == Debug.dbswtch):
  27.                     print("debug on")
  28.                 else:
  29.                     print("debug off")
  30.             elif(cmd == "exit"):
  31.                 exit(1)
  32.             else:
  33.                 self.menu()
  34.         return
  35. class TcpClient(threading.Thread):
  36.     def __init__(self, c_socket, c_address):
  37.         threading.Thread.__init__(selfNone)
  38.         self.socket = c_socket
  39.         self.address = c_address
  40.         Debug.out(("connect in %s" % str(c_address)))
  41.     def run(self):
  42.         while(True):
  43.             data = self.socket.recv(1024)
  44.             Debug.out(("recieve data:%s" % str(data)))
  45.             if(len(data) > 0):
  46.                 try:
  47.                     self.socket.send(data)
  48.                 except:
  49.                     Debug.out(("recieve data error from %s" % str(self.address)))
  50.                     break
  51.             else:
  52.                 self.socket.close()
  53.                 Debug.out(("%s connection close" % str(self.address)))
  54.                 break
  55. class TcpServer:
  56.     def __init__(self):
  57.         s_socket = socket.socket()
  58.         s_socket.bind((''20001))
  59.         s_socket.listen(10)
  60.         print("ok2")
  61.         while(True):
  62.             print("ok3")
  63.             c_socket,c_address = s_socket.accept()
  64.             Debug.out("someone call me")
  65.             c_thread = TcpClient(c_socket, c_address)
  66.             c_thread.start()
  67. def main():
  68.     cmd = Cmd()
  69.     cmd.start()
  70.     print("ok1")
  71.     tcps = TcpServer()
  72.     
  73. if __name__ == "__main__":
  74.     main()
  75.     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值