37,722
社区成员
发帖
与我相关
我的任务
分享
import socket, sys, time, struct
import pdb
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#------------------------------------------------------
# Print the struct.pack Binary content as Hex
# 16 bytes per line
#------------------------------------------------------
def PrintBinHex(s, flag):
global dbugFlag
# dbug < 0: accurate output
# dbug >=0: range output
if(dbugFlag < 0):
if(flag != -1*dbugFlag):
return
elif(flag < dbugFlag):
return
bytes = bytearray(s)
cnt = 0
for i in bytes:
cnt=cnt+1
print "%02x" % i,
if (cnt%16) == 0:
print "\n"
elif (cnt%8) == 0:
print " ",
print
#------------------------------------------------------
# InitFrontEnd
# connect to the target
#------------------------------------------------------
def InitFrontEnd():
print "Connect to host..."
try:
port = 123456
host = "192.168.1.100"
serverSocket.connect((host, port))
except socket.error, e:
print "Connection error: %s" % e
sys.exit(1)
else:
print "Connection succ..."
#------------------------------------------------------
# RecvN
# recv N bytes to target
#------------------------------------------------------
def RecvN(socket, n):
return socket.recv(n)
#------------------------------------------------------
# Recv Fake Rsp Info from server
# get only 1 int16 first for msg len and then msg body from server to test the connection
#------------------------------------------------------
def RecvWholeMsgFromServer():
global serverSocket
#print "try to get... "
#pdb.set_trace()
lenBuf = ''
length = 0
try:
lenBuf = RecvN(serverSocket, 2)
length, = struct.unpack('!H', lenBuf)
bodyBuf = RecvN(serverSocket, length-2)
Msg = lenBuf + bodyBuf
except :
print "****** Except Length : %d *******\n" %length
PrintBinHex(lenBuf, 1)
raise
#------------------------------------------------------
# Get Msg from Server
# RecvLoop
#------------------------------------------------------
def RecvLoop():
x = 1
while x <= 100:
RecvWholeMsgFromServer()
x+=1
if x % 10 == 0:
print "Recv [%d]" % x
#------------------------------------------------------
# connect to server and get msg
#
#------------------------------------------------------
def FrontEndConnAndRecv():
# 1. client connect BackEnd
InitFrontEnd()
#time.sleep(10) <------------------------ 如果不加这里,RecvN会返回空字符串
RecvLoop()
#------------------------------------------------------
# RecvN
# recv N bytes to target
#------------------------------------------------------
def RecvN(socket, n):
totalContent = ''
totalRecved = 0
while totalRecved < n:
onceContent = socket.recv(n - totalRecved)
totalContent += onceContent
totalRecved = len(totalContent)
return totalContent
...
lenBuf = RecvN(serverSocket, 2)
length, = struct.unpack('!H', lenBuf)
bodyBuf = RecvN(serverSocket, length-2)
Msg = lenBuf + bodyBuf
可能的问题:
1. recv(n)有可能接收到少于n个byte的信息, 所以recv(n)后要检查接收到的信息长度, 不够的话再调用recv接收.
1. 数据流格式你理解的对不对?数据流是否正确? (听起来有点冒犯, 但这确实是一个问题, 比如length好象表示信息的长度, 它包括length所用的两个byte吗?)