c++ websocket客户端示例
时间: 2023-04-04 07:01:21 浏览: 110
你可以参考以下代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <server_ip> <port>\n", argv[]);
exit(1);
}
char *server_ip = argv[1];
int port = atoi(argv[2]);
// 创建 socket
int sockfd = socket(AF_INET, SOCK_STREAM, );
if (sockfd < ) {
perror("socket");
exit(1);
}
// 设置服务器地址
struct sockaddr_in server_addr;
memset(&server_addr, , sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(server_ip);
server_addr.sin_port = htons(port);
// 连接服务器
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < ) {
perror("connect");
exit(1);
}
// 发送数据
char buf[BUF_SIZE];
sprintf(buf, "GET / HTTP/1.1\r\n"
"Host: %s:%d\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n", server_ip, port);
if (send(sockfd, buf, strlen(buf), ) < ) {
perror("send");
exit(1);
}
// 接收数据
int n;
char recv_buf[BUF_SIZE];
while ((n = recv(sockfd, recv_buf, BUF_SIZE, )) > ) {
recv_buf[n] = '\';
printf("%s", recv_buf);
}
// 关闭 socket
close(sockfd);
return ;
}
阅读全文