Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将int和bytearray转换为ByteString Python结构套接字_Python_Sockets_Struct_Byte_Bytearray - Fatal编程技术网

将int和bytearray转换为ByteString Python结构套接字

将int和bytearray转换为ByteString Python结构套接字,python,sockets,struct,byte,bytearray,Python,Sockets,Struct,Byte,Bytearray,我需要通过套接字将1 int和1 bytearray(200)发送到服务器。 send()函数只接受一个字符串,所以我需要int和bytearray作为一个字符串中的字节。 我尝试使用struct.pack()将两者转换为字符串,这对于int很有效,但对于bytearray则不行 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) print "Connec

我需要通过套接字将1 int和1 bytearray(200)发送到服务器。 send()函数只接受一个字符串,所以我需要int和bytearray作为一个字符串中的字节。 我尝试使用struct.pack()将两者转换为字符串,这对于int很有效,但对于bytearray则不行

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    print "Connected to: ",  s.getpeername()
    #Trying to put int and bytearray into 1 string
    a= 02 # int
    b= bytearray(200) #bytearray
    c = struct.pack("B", a)
    c += b



    s.send(c)
    print s.recv(1024)
连接它们:

>>> import struct
>>> struct.pack('<l', 1234) + bytearray([0]*10)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
导入结构
>>>struct.pack('你能显示代码吗?我知道它不能这样工作,但到目前为止我没有任何bytearray的解决方案。.到底什么不起作用?我需要用字节码发送int和数组(200字节,但数组是空的)。如果我使用Falstru的解决方案,我会得到一个未处理的typeerror“bytearray对象不可调用”,如果尝试使用我的代码,则不会出现错误,但服务器不会接收该消息。我不明白您的bytearray为何为空。我刚刚在客户端和服务器之间成功测试了这一点。我的服务器使用与您完全相同的代码以我发送的完全相同的方式回复。您可以将数组显示为空吗?包装是否应该为big-endian?我的校验和是incor当发送尽可能小的尾数时使用rect。@EugeneC.,这取决于对手的期望。正如您所知,很容易生成大尾数/网络尾数压缩字节。(
而不是
,也不确定这是否是特定于版本的,但是如果bytearray不是转换为字符串,则您的第二个结构示例会出错。我正在运行2.7。5@EugeneC.,你说得对。第二个代码应该调整。我根据你的评论更新了答案。谢谢。
>>> struct.pack('<l10s', 1234, bytearray([0]*10)) # In Python 3.x
# struct.pack('<l10s', 1234, bytes(bytearray([0]*10))) # In Python 2.x
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'