python socket recv接收网络数据返回空字符串,该如何解决

python socket recv接收网络数据返回空字符串
本帖最后由 lday 于 2014-10-09 17:09:00 编辑
在与服务器建立连接后通过
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
接收来自后台的消息,
通过socket.recv(n)接收消息,有时候会接收到空字符串,但通过抓包发现服务器端发送过来的并非空字符串。
但如果在recv前面先sleep(10),再接收就没有这个问题, 很奇怪,感觉像是recv太快了... 我没有设置socket选项,应该默认是阻塞io,求解释。

************ 但如果sleep(2),还是有可能出现,只是不再最开始出现。

client端代码如下:


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()


=========================================================
执行结果如下:

Connect to host...
Connection succ...
****** Except Length : 0 *******

00 00
Traceback (most recent call last):
  File "R:\Project\MyTest1\sources\tools\MyTool1\MyTest1_SendAndRecvTest
\FrontEnd.py", line 317, in <module>
    FrontEndConnAndRecv()
  File "R:\Project\MyTest1\sources\tools\MyTool1\MyTest1_SendAndRecvTest
\FrontEnd.py", line 268, in FrontEndConnAndRecv
    RecvLoop()
  File "R:\Project\MyTest1\sources\tools\MyTool1\MyTest1_SendAndRecvTest
\FrontEnd.py", line 252, in RecvLoop
    RecvWholeMsgFromServer()
  File "R:\Project\MyTest1\sources\tools\MyTool1\MyTest1_SendAndRecvTest
\FrontEnd.py", line 237, in RecvWholeMsgFromServer
    bodyBuf = RecvN(serverSocket, length-2)
  File "R:\Project\MyTest1\sources\tools\MyTool1\MyTest1_SendAndRecvTest
\FrontEnd.py", line 105, in RecvN
    return socket.recv(n)
ValueError: negative buffersize in recv

---------------------------------------------------------------------------