使用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设计】。

相关文章

python3库numpy数组属性的查看方法

实例如下所示: import numpy as np a1 = np.array([1,2,3,4],dtype=np.complex128) print(a1) print("数据...

Python网页解析利器BeautifulSoup安装使用介绍

Python网页解析利器BeautifulSoup安装使用介绍

python解析网页,无出BeautifulSoup左右,此是序言 安装 BeautifulSoup4以后的安装需要用eazy_install,如果不需要最新的功能,安装版本3就够了,千...

python两种遍历字典(dict)的方法比较

python以其优美的语法和方便的内置数据结构,赢得了不少程序员的亲睐。其中有个很有用的数据结构,就是字典(dict),使用非常简单。说到遍历一个dict结构,我想大多数人都会想到 fo...

Python使用Pandas对csv文件进行数据处理的方法

Python使用Pandas对csv文件进行数据处理的方法

今天接到一个新的任务,要对一个140多M的csv文件进行数据处理,总共有170多万行,尝试了导入本地的MySQL数据库进行查询,结果用Navicat导入直接卡死....估计是XAMPP套...

Python除法之传统除法、Floor除法及真除法实例详解

先给大家介绍下Python除法之传统除法、Floor除法及真除法 python3.0 /总是执行真除法,不管操作数的类型,都返回浮点数结果(即使能整除,如4/2==2.0); //执...