Python套接字,初始传输后没有数据收到

时间:2013-09-09 17:51:12

标签: python sockets networking

我正在寻找一个非常基本的远程桌面应用程序。现在我能够使用python win32 API捕获屏幕数据,并且我能够通过套接字连接发送一个图像,并在接收端正确地重建它。在发送实际图像数据之前,我发送图像的大小和一些编码为11字节字符串的其他数据。我遇到的问题是当我尝试发送第二个11字符串时。简单地说,没有数据通过套接字。客户端发送数据,打印出确认其进度的一些信息然后关闭。但在服务器端,没有数据通过套接字。我不确定发生了什么。

这是我的代码,在线注释:

客户端:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 8888))

imgLength = sys.getsizeof(bmpstr)    ## bmpstr is the pixel data
prefix = str(imgLength) # message length
prefixSize = sys.getsizeof(prefix)
if prefixSize < 30:
    prefix = ('0' * (30 - prefixSize)) + prefix
    prefix = "5" + "1" + prefix  ## BLOCK LOCATION    
s.send(prefix.encode("UTF-8"))

totalSent = 0
while totalSent < imgLength:
    totalSent += 4096
    if (totalSent >= imgLength):
        s.send(bmpstr[totalSent :])
        break
    else:
        s.send(bmpstr[totalSent : totalSent + 4096])

现在我只需运行两次,以相同的方式发送前缀和像素数据。它的字面意思是复制和粘贴。我不关闭套接字,我对两个图像使用相同的连接。我想知道这可能是我的问题吗?我希望有一些实时的数据传输,可能是3-4 FPS,所以我希望尽可能高效地完成这项工作。

服务器端:

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8888))
serversocket.listen(5)

transmission = clientsocket.recv(4096)
transmissionMetaData = decode_meta_data(transmission)
transmissionLength = transmissionMetaData[0]
blockX = transmissionMetaData[1]
blockY = transmissionMetaData[2]

while 1:
    thisData = clientsocket.recv(4096)
    data += thisData
    if len(data) >= transmissionLength or not(thisData):
        break

## rebuild the image...

# prepare for second image
data = ""
transmission = ""
prefixTransmission = ""

## here is the problem, I am trying to receive the prefix data which will contain 
# the size of the second transmission. But for some reason this never gets any data
# it works just fine when i do it above.
while 1:
    thisData = clientsocket.recv(4096)
    prefixTransmission += thisData
    ### this line always prints an empty string for the data
    print sys.getsizeof(prefixTransmission), "   :", prefixTransmission
    if sys.getsizeof(prefixTransmission) >= 32:
        transmissionMetaData = prefixTransmission[0:11]
        if sys.getsizeof(prefixTransmission) > 32:  
            data = prefixTransmission[11:]
        break

transmissionMetaData = decode_meta_data(transmission)
transmissionLength = transmissionMetaData[0]
blockX = transmissionMetaData[1]
blockY = transmissionMetaData[2]

while 1:
    thisData = clientsocket.recv(4096)
    data += thisData
    if len(data) >= transmissionLength or not(thisData):
        break

所以我目前的问题是,第二段元数据根本就不是通过套接字传递的。如果我只发送11个字符的元数据,那么程序会挂起一个空的传输。如果我让客户端发送11个字符的元数据,然后是图像数据本身,则服务器崩溃,因为它无法解码前11个字节。

UnicodeDecodeError: 'utf8' cannot decode byte 0xff in position 2: invalid start byte

我想也许我不正确地拔出了11个字符?

0 个答案:

没有答案