SylixOS嵌入式操作系统|论坛
标题:
采用vsoa架构的 client示例代码
[打印本页]
作者:
yuqing
时间:
2022-12-22 19:11
标题:
采用vsoa架构的 client示例代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef SYLIXOS
#include <sys/vproc.h>
#endif
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "vsoa_client.h"
#include "vsoa_position.h"
#include "vsoa_platform.h"
#include "foo_jstruct.h"
/* My server password */
#define MY_SERVER_PASSWD "123456"
/* My client */
static vsoa_client_t *client;
/*
* On message
*/
static void onmessage (void *arg, struct vsoa_client *client, vsoa_url_t *url, vsoa_payload_t *payload)
{
printf("On message, URL: %.*s payload: %.*s\n",
(int)url->url_len, url->url, (int)payload->param_len, payload->param);
}
/*
* Get foo callback
*/
static void get_foo (void *arg, struct vsoa_client *client, vsoa_header_t *vsoa_hdr, vsoa_payload_t *payload)
{
struct data data;
if (!vsoa_hdr) {
fprintf(stderr, "VSOA server /foo reply timeout!\n");
return;
}
if (!foo_json_parse(&data, payload->param, payload->param_len)) {
fprintf(stderr, "VSOA server /foo reply format error!\n");
return;
}
printf("RPC /foo reply foo: %d\n", data.foo);
foo_json_parse_free(&data);
}
/*
* main function
*/
int main (int argc, char **argv)
{
int max_fd, cnt;
fd_set fds;
char info[256];
time_t now, last;
vsoa_url_t url;
socklen_t serv_len = sizeof(struct sockaddr_in);
struct sockaddr_in addr;
struct timespec timeout = { 1, 0 };
#ifdef SYLIXOS
vprocExitModeSet(getpid(), LW_VPROC_EXIT_FORCE);
#endif
if (!vsoa_position_lookup(AF_INET, "c_server",
(struct sockaddr *)&addr, &serv_len, NULL, &timeout)) {
fprintf(stderr, "Can not found VSOA server!\n");
return (-1);
}
client = vsoa_client_create(onmessage, NULL);
if (!client) {
fprintf(stderr, "Can not create VSOA client!\n");
return (-1);
}
if (!vsoa_client_connect(client, (struct sockaddr *)&addr, sizeof(struct sockaddr_in),
&timeout, MY_SERVER_PASSWD, info, sizeof(info))) {
vsoa_client_close(client);
fprintf(stderr, "Can not connect to VSOA server!\n");
return (-1);
}
printf("Server (%s) connected\n", info);
url.url = "/foo";
url.url_len = strlen(url.url);
vsoa_client_subscribe(client, &url, NULL, NULL, NULL);
time(&last);
while (1) {
FD_ZERO(&fds);
max_fd = vsoa_client_fds(client, &fds);
cnt = pselect(max_fd + 1, &fds, NULL, NULL, &timeout, NULL);
if (cnt > 0) {
if (!vsoa_client_input_fds(client, &fds)) {
fprintf(stderr, "Connection lost!\n");
return (-1);
}
}
time(&now);
if (now - last >= 5) {
last = now;
if (!vsoa_client_call(client, VSOA_CLIENT_RPC_METHOD_GET,
&url, NULL, get_foo, NULL, &timeout)) {
vsoa_client_close(client);
fprintf(stderr, "Can not RPC call to VSOA server!\n");
return (-1);
}
}
}
}
/*
* end
*/
欢迎光临 SylixOS嵌入式操作系统|论坛 (https://bbs.sylixos.com/)
Powered by Discuz! X3.2