Reputation: 111
I created a socket server in C (using nanomsg) which shall communicate with a Python script (using standard 'Socket' implementation) via TCP:
C-Code (without error handling):
#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);
Python-Code:
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()
There is no error in Python when connecting to the socket (if the C app is running). However, the C script is idling in method nn_recv and doesn't get any data at all. What am I doing wrong?
First I start the C code in a shell (it idles in method nn_recv). Then I start Python in another shell and expect the C application to receive the data. Both scripts execute without error.
Upvotes: 3
Views: 1593
Reputation: 6298
The issue is that nanomsg socket type is not a plain, standard, TCP type. The protocols do not match. You cannot send TCP message to a nanomsg socket and expect that nn_recv
will work since the message will not conform to the defined nanomsg SP protocol requirements.
See nanomsg SP protocol header:
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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
First four bytes of the protocol header are used to make sure that the peer's protocol is compatible with the protocol used by the local endpoint.
If the protocol header received from the peer differs, the TCP connection MUST be closed immediately.
That means that any raw TCP send
to the nanomsg socket will kill the connection since it does not confirm to the SP protocol.
For more info consult the sp-tcp-mapping-01.txt document here
Upvotes: 5