使用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设置默认编码为utf8的方法

本文实例讲述了Python设置默认编码为utf8的方法。分享给大家供大家参考,具体如下: 这是Python的编码问题,设置python的默认编码为utf8 python安装目录:/etc...

Python3多线程操作简单示例

本文实例讲述了Python3多线程操作。分享给大家供大家参考,具体如下: python3 线程中常用的两个模块为: _thread threading(推荐使用) thread 模块已被...

Python实现二维数组输出为图片

对于二维数组,img_mask [[ 0 0 0 ..., 7 7 7] [ 0 0 0 ..., 7 7 7] [ 0 0 0 ..., 7 7 7] ..., [266...

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

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

Python 硬币兑换问题

硬币兑换问题: 给定总金额为A的一张纸币,现要兑换成面额分别为a1,a2,....,an的硬币,且希望所得到的硬币个数最少。 # 动态规划思想 dp方程式如下 # dp[0] =...