libwebsockets domo
时间: 2023-07-30 16:09:20 浏览: 149
以下是使用 libwebsockets 实现一个简单的 WebSocket 服务器和客户端的示例:
服务器端代码:
```c
#include <libwebsockets.h>
#include <string.h>
#include <stdio.h>
static int callback_echo(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len)
{
switch (reason) {
case LWS_CALLBACK_ESTABLISHED: {
printf("connection established\n");
break;
}
case LWS_CALLBACK_RECEIVE: {
char buf[1024];
strncpy(buf, (char *)in, len);
buf[len] = '\0';
printf("received message: %s\n", buf);
lws_write(wsi, (unsigned char *)in, len, LWS_WRITE_TEXT);
break;
}
default:
break;
}
return 0;
}
static struct lws_protocols protocols[] = {
{
"echo-protocol",
callback_echo,
0,
1024,
},
{ NULL, NULL, 0, 0 }
};
int main(void)
{
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
info.port = 8000;
info.protocols = protocols;
struct lws_context *context;
context = lws_create_context(&info);
if (!context) {
printf("Failed to create libwebsocket context\n");
return -1;
}
while (1) {
lws_service(context, 50);
}
lws_context_destroy(context);
return 0;
}
```
客户端代码:
```c
#include <libwebsockets.h>
#include <string.h>
#include <stdio.h>
static int callback_echo(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len)
{
switch (reason) {
case LWS_CALLBACK_CLIENT_ESTABLISHED: {
printf("connection established\n");
lws_write(wsi, (unsigned char *)"Hello, server!", 14, LWS_WRITE_TEXT);
break;
}
case LWS_CALLBACK_CLIENT_RECEIVE: {
char buf[1024];
strncpy(buf, (char *)in, len);
buf[len] = '\0';
printf("received message: %s\n", buf);
break;
}
default:
break;
}
return 0;
}
static struct lws_protocols protocols[] = {
{
"echo-protocol",
callback_echo,
0,
1024,
},
{ NULL, NULL, 0, 0 }
};
int main(void)
{
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
info.port = CONTEXT_PORT_NO_LISTEN;
info.protocols = protocols;
struct lws_context *context;
context = lws_create_context(&info);
if (!context) {
printf("Failed to create libwebsocket context\n");
return -1;
}
struct lws_client_connect_info connect_info;
memset(&connect_info, 0, sizeof(connect_info));
connect_info.context = context;
connect_info.address = "localhost";
connect_info.port = 8000;
connect_info.path = "/";
connect_info.host = "localhost";
connect_info.origin = "http://localhost";
struct lws *wsi;
wsi = lws_client_connect_via_info(&connect_info);
if (!wsi) {
printf("Failed to connect to server\n");
lws_context_destroy(context);
return -1;
}
while (1) {
lws_service(context, 50);
}
lws_context_destroy(context);
return 0;
}
```
以上代码实现了一个简单的 WebSocket 服务器和客户端,服务器收到客户端发送的消息后,会将消息原样返回给客户端。
阅读全文