写一段websocket的示例程序
时间: 2023-03-27 22:04:55 浏览: 71
好的,以下是一个简单的 WebSocket 示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 808
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {};
char *hello = "Hello from server";
// 创建 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, )) == ) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置地址和端口
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// 绑定 socket
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < ) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听 socket
if (listen(server_fd, 3) < ) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < ) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 发送欢迎消息
send(new_socket, hello, strlen(hello), );
printf("Hello message sent\n");
// 接收消息
int valread;
while ((valread = read(new_socket, buffer, 1024)) > ) {
printf("%s\n", buffer);
send(new_socket, buffer, strlen(buffer), );
memset(buffer, , sizeof(buffer));
}
return ;
}
```
这个程序创建了一个 WebSocket 服务器,监听 808 端口。当客户端连接上来后,服务器会发送一条欢迎消息,然后不断接收客户端发送的消息,并将其原样返回给客户端。
阅读全文