使用python编写监听端

yipeiwu_com6年前Python基础

本文实例为大家分享了python编写监听端的具体代码,供大家参考,具体内容如下

import socket 
import time 
import sys 
import string 
import struct 
import errno 
import binascii 
 
#Definition 
ser_ip = 'localhost' 
ser_port = 15001 
HEADER_LISTENER = "IIII" 
split_time = 4 
 
class TcpClient: 
 
 def run_srv(self): 
  sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
 
  print ("Trying to connect server...") 
 
  addr = (ser_ip, ser_port) 
   
  print ("Connecting " + ser_ip + ":" + str(ser_port)) 
 
  #Connect server 
  try: 
    sock.connect(addr) 
  except Exception,e: 
    print ("Error:%s" % (e)) 
    sock.close() 
    sys.exit() 
 
  hl = struct.pack(HEADER_LISTENER,0,0,0,0) 
  header_len = len(hl) 
   
  while True: 
    try: 
      buf_recv = sock.recv(header_len) 
    buf_header = buf_recv[0:header_len]      
      thread_id = struct.unpack("!4I" , buf_header)[0] 
    err_num = struct.unpack("!4I" , buf_header)[1] 
    com_num = struct.unpack("!4I" , buf_header)[2] 
    wait_num = struct.unpack("!4I" , buf_header)[3] 
    #print("header len %d, recv len %d,buf_header:%s,buf_recv:%s")%(header_len,len(buf_recv),binascii.hexlify(buf_header),binascii.hexlify(buf_recv)) 
      print ("split time:%d")%(split_time) 
      print ("thread id :%d")%(thread_id) 
      print ("error nums:%d")%(err_num) 
      print ("compl nums:%d")%(com_num) 
      print ("wait nums:%d")%(wait_num) 
      print ("----------------------") 
    except Exception,e: 
      print ("Error:%s" % (e)) 
      sock.close() 
      sys.exit() 
       
 
if __name__ == '__main__': 
  if (len(sys.argv) >= 2): 
    ser_port = int(sys.argv[1]) 
   
  client = TcpClient() 
  client.run_srv() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python内置模块collections知识点总结

python内置模块collections介绍 collections是Python内建的一个集合模块,提供了许多有用的集合类。 1、namedtuple python提供了很多非常好用...

分享Python开发中要注意的十个小贴士

大家请注意:这篇文中假设我们都用的是Python 3 1. 列表推导式 你有一个list:bag = [1, 2, 3, 4, 5] 现在你想让所有元素翻倍,让它看起来是这个样子: [2...

Python使用selenium + headless chrome获取网页内容的方法示例

使用python写爬虫时,优选selenium,由于PhantomJS因内部原因已经停止更新,最新版的selenium已经使用headless chrome替换掉了PhantomJS,所...

深入解析Python中函数的参数与作用域

传递参数 函数传递参数时的一些简要的关键点: 参数的传递是通过自动将对象赋值给本地变量名来实现的。所有的参数实际上都是通过指针进行传递的,作为参数被传递的对象从来不自动拷贝。...

Python利用WMI实现ping命令的例子

WMI是Windows系统的一大利器,Python的win32api库提供了对WMI的支持,安装win32api即可使用 WMI。 本例通过WMI的WQL实现ping命令。 impo...