Last active
March 1, 2024 20:43
-
-
Save yuanfeiz/6290017 to your computer and use it in GitHub Desktop.
My first socket program using nanomsg as in-proc communication method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <nanomsg/nn.h> | |
#include <nanomsg/pair.h> | |
#include <stdio.h> | |
int main() { | |
int s = nn_socket(AF_SP, NN_PAIR); | |
int nbytes; | |
char ch; | |
char str[100]; | |
nn_connect(s, "ipc://test.ipc"); | |
while (ch = getchar()) { | |
sprintf(str, "%c\0", ch); | |
nbytes = nn_send(s, str, 2, 0); | |
if (nbytes < 0) | |
printf("%s\n", nn_strerror(errno)); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <nanomsg/nn.h> | |
#include <nanomsg/pair.h> | |
#include <stdio.h> | |
#include <assert.h> | |
int main() { | |
int s = nn_socket(AF_SP, NN_PAIR); | |
char buf[100]; | |
int nbytes; | |
assert(s >= 0); | |
nn_bind(s, "ipc://test.ipc"); | |
while (1) { | |
nbytes = nn_recv(s, buf, sizeof(buf), 0); | |
if (nbytes < 0) | |
printf("%s\n", nn_strerror(errno)); | |
else | |
printf("%s", buf); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <nanomsg/nn.h> | |
#include <nanomsg/pair.h> | |
#include <assert.h> | |
#include <stdio.h> | |
#include <nanomsg/inproc.h> | |
int handle_error() { | |
printf("%s\n", nn_strerror(errno)); | |
return 0; | |
} | |
int main() { | |
int sa = nn_socket(AF_SP, NN_PAIR); | |
int sb = nn_socket(AF_SP, NN_PAIR); | |
int eid1, eid2; | |
char buf[100]; | |
int nbytes; | |
assert(sa >= 0); | |
eid2 = nn_connect(sa, "inproc://test"); | |
assert(eid2 >= 0); | |
eid1 = nn_bind(sb, "inproc://test"); | |
assert(eid1 >= 0); | |
nbytes = nn_send(sa, "def\0", 4, 0); | |
nbytes = nn_recv(sb, buf, sizeof(buf), 0); | |
if (nbytes >= 0) | |
printf("%s\n", buf); | |
else { | |
handle_error(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The trap is when initializing socket using
nn_socket
. I first triedNN_PUB
, and failed for a thousand times, after changed to NN_PAIR, everything was fine.