0

我想在套接字上发送一个文件,并且需要在前四个字节中传递它的长度。

这是我想在 C 中做的事情:

struct
{
  int lenght; //four bytes
  char msg[40];
}dataBuf;

write(fd, &databuf, sizeof(dataBuf))

如何将整数推送到套接字上,以便它在另一端将其作为整数而不是 ASCII 值接收?

我不想像“ \x04\X03”一样硬编码它,我试着用pack(L*). 这只适用于数组,我没有办法将我的四字节整数分解为四字节数组。

4

2 回答 2

4

Try putting the integer into an array and then using pack. For example:

socket.write( [0xffff].pack("L") )
于 2012-07-24T20:58:56.757 回答
1

查看BinData gem。

您的示例可能如下所示:

class DataBuf < BinData::Record
  uint32 :length
  array :msg, :initial_length => 40 do
    uint8
  end
end

io = File.open(...)
r = DataBuf.read(io)
puts "Data buffer is #{r.length} length and it has '#{r.msg}' message"

我不确定消息,您应该查看 BinData 文档的字符串部分。

于 2012-07-24T21:18:45.157 回答