C語言是一門廣泛應(yīng)用于計(jì)算機(jī)編程的高級(jí)編程語言。它可以用于系統(tǒng)軟件、應(yīng)用軟件、驅(qū)動(dòng)程序以及網(wǎng)絡(luò)協(xié)議等各類領(lǐng)域。最近,隨著現(xiàn)代Web應(yīng)用的流行,我們越來越需要使用WebSocket發(fā)送JSON數(shù)據(jù),而C語言正是我們可以使用的語言。下面我們來詳細(xì)了解一下相關(guān)內(nèi)容。
//引用頭文件
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "openssl/crypto.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
int main(int argc, char **argv) {
struct sockaddr_in serv_sock;
char send_buffer[1024], recv_buffer[1024];
SSL_library_init();
//創(chuàng)建Socket
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sockfd == -1) {
printf("Failed to create socket!");
exit(1);
}
memset(&serv_sock, 0, sizeof(serv_sock));
serv_sock.sin_family = AF_INET;
serv_sock.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_sock.sin_port = htons(8888);
//建立連接
if(connect(sockfd, (struct sockaddr *)&serv_sock, sizeof(serv_sock)) == -1) {
printf("Failed to connect!");
exit(1);
}
printf("Connect to server successfully.\n");
//準(zhǔn)備要發(fā)送的JSON數(shù)據(jù)
char *json_str = "{\"message\":\"Hello world!\"}";
sprintf(send_buffer, "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\nContent-Type: application/json\r\nContent-Length: %ld\r\n\r\n%s", "x3JJHMbDL1EzLkh9GBhXDw==", strlen(json_str), json_str);
//發(fā)送WebSocket請求
int len = strlen(send_buffer);
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd);
SSL_connect(ssl);
SSL_write(ssl, send_buffer, len);
//接收WebSocket響應(yīng)
int recv_len = SSL_read(ssl, recv_buffer, sizeof(recv_buffer) - 1);
recv_buffer[recv_len] = '\0';
printf("Received:\n%s\n", recv_buffer);
SSL_shutdown(ssl);
SSL_free(ssl);
close(sockfd);
return 0;
}
WebSocket是一種被設(shè)計(jì)用于基于Web的協(xié)議的全雙工通信,可以開啟到瀏覽器和服務(wù)器之間的雙向通信。這段代碼讓我們創(chuàng)建了一個(gè)socket,建立連接并向服務(wù)器發(fā)送JSON數(shù)據(jù),實(shí)現(xiàn)了WebSocket發(fā)送JSON數(shù)據(jù)。