正在更新我的应用程序,该应用程序使用套接字从 python 到 C 程序进行通信,以便在发送消息时使用固定长度的标头作为协议。
作为我的 C 客户端代码的测试示例:
/*
Socket definition code put inside here
*/
char test2[] = "hello this is a test";
uint32_t test = sizeof(test2); //Get size of message and store in 32bit int
uint32_t test_conv = htonl(test); //Convert to network byte order
header = send(ConnectSocket, &test_conv, sizeof(uint32_t), 0); //Send size of message
body = send(ConnectSocket, test2, sizeof(test2), 0); //Send the actual message
这是python服务器代码的摘录:
msg = clientsocket.recv(4)
msg_length = int.from_bytes(msg, sys.byteorder) //Get the header with the message length
msg_length = socket.ntohl(msg_length)
if len(msg) > 0:
print(f"This message length: {test} ")
msg = clientsocket.recv(msg_length) //Get the message
if len(msg)>0:
print(f'Message is: {msg.decode("utf-8")}')
服务器.py 输出:
The message length: 21
Message is: hello this is a test
我在这篇文章中省略了套接字头和其他内容以及错误检查以节省空间。
这是使用固定长度标头的安全方法吗?我并不期待大量的流量,我只会在每条消息中发送一两句话的信息。
我的最后一个问题是为什么在 C 中调用 send 时我使用 '&test_conv' 作为消息参数。这不仅仅是发送 test_conv 变量的地址值。我不需要发送实际消息,而不是地址吗?
感谢您提供任何见解,如果我应该使用不同的实现,请提供任何资源链接。