// Not thread safe
zmq_socket
void* zmq_socket(void* context, int type);
This API will create an opaque socket handle according to the context, type . And the connection is not initialized
It is not associated with any port . If it is a client , then you need to use zmq_connect to connect to the server
If it is a server , you need to use the zmq_bind API to bind the port .
Unlike traditional sockets , traditional sockets are either a stream protocol or a message protocol.
While zmq 's socket proposes an asynchronous message queue , and with accurate queue semantics , the previous implementation relies on
type, that is, the different socket types used
And ZMQ transmits unsecured messages
context : can be obtained from zmq_ctx_new() apI
type: indicates what type of socket you need to create
type:
Request - Reply Model (ZMQ-REQ)
The model is used to send requests from a client to one or more servers , and the servers make requests for each request .
If no server exists , the client will group , until a server becomes available , its server operation is zmq_recv, zmq_send. That is, it is used alternately , which is very suitable for http servers .
For the client , you need to send first, then recv
exqmple:
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#include <zmq.h>
}
#pragma comment(lib,"libzmq_d.lib")
#define buffersize 4096
int main(int argc, char* argv[])
{
void * ctx = zmq_ctx_new();
void* server = zmq_socket(ctx, ZMQ_REQ);
zmq_connect(server, "tcp://localhost:5050");
char* buffer[256] = { 0 };
int ret = 0;
char* str = "我是客户端.....";
while (true)
{
memset(buffer, 0, 256);
zmq_send(server, str, strlen(str), 0);
zmq_recv(server, buffer, 256, 0);
printf("%s\n", buffer);
}
system("pause");
zmq_close(server);
zmq_ctx_destroy(ctx);
return 0;
}
ZMQ_REP模式
该模型用于 服务器 去接受请求, 并对接受的请求做出相应的套接字模式 , 即先 recv, 再 send
example :
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#include <zmq.h>
}
#pragma comment(lib,"libzmq_d.lib")
#define buffersize 4096
int main(int argc, char* argv[])
{
void * ctx = zmq_ctx_new();
void* server = zmq_socket(ctx, ZMQ_REQ);
zmq_connect(server, "tcp://localhost:5050");
char* buffer[256] = { 0 };
int ret = 0;
char* str = "我是客户端.....";
while (true)
{
memset(buffer, 0, 256);
zmq_send(server, str, strlen(str), 0);
zmq_recv(server, buffer, 256, 0);
printf("%s\n", buffer);
}
system("pause");
zmq_close(server);
zmq_ctx_destroy(ctx);
return 0;
}