C(nanomsg)和Python(非nanomsg)之间的套接字连接

lin*_*ate 3 c python sockets python-2.7 nanomsg

我在C中创建了一个套接字服务器(使用nanomsg),它将通过TCP与Python脚本(使用标准的"Socket"实现)进行通信:

C代码(无错误处理):

#include <nanomsg/nn.h>
#include <nanomsg/pair.h>
...
char buf[23];
...
socket = nn_socket(AF_SP, NN_PAIR);
nn_bind(socket, "tcp://127.0.0.1:xxxxx");
...
nn_recv(socket, buf, sizeof(buf), 0); 
...
nn_shutdown(socket, endpoint_id);
Run Code Online (Sandbox Code Playgroud)

Python的代码:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect(("127.0.0.1", xxxxx))
s.send('Hello C this is Python')
s.close()
Run Code Online (Sandbox Code Playgroud)

连接到套接字时,Python中没有错误(如果C应用程序正在运行).但是,C脚本在方法nn_recv中空闲,并且根本不获取任何数据.我究竟做错了什么?

首先,我在shell中启动C代码(它在方法nn_recv中空闲).然后我在另一个shell中启动Python并期望C应用程序接收数据.两个脚本都可以正确执行.

sg7*_*sg7 5

问题是nanomsg套接字类型不是普通的标准TCP类型.协议不匹配.您不能将TCP消息发送到nanomsg套接字并期望nn_recv它将起作用,因为该消息将不符合定义的nanomsg SP协议要求.

请参阅nanomsg SP协议标题:

0                1               2                3
0 1 2 3 4 5 6 7  8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3  4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      0x00     |      0x53     |      0x50     |    version    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|             type              |           reserved            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Run Code Online (Sandbox Code Playgroud)

协议头的前四个字节用于确保对等方的协议与本地端点使用的协议兼容.

如果从对等方收到的协议头不同,则必须立即关闭TCP连接.

这意味着任何send到nanomsg套接字的原始TCP 将终止连接,因为它不会向SP协议确认.

欲了解更多信息请咨询SP-TCP映射-01.txt文件在这里