Websocket连接过早地关闭连接

所以,我正在尝试构建一个充当Websockets Server的C应用程序。这里有很多相关的问题,但它们似乎都没有能够帮助解决这个问题。 该程序能够初始建立连接,成功完成websocket的握手,但是,似乎无法保持连接打开。 在客户端,我收到错误

WebSocket.js:7605未捕获错误:尝试在未打开或关闭的WebSocket上发送消息,位于_8b2.window.WebSocket._8d2.send(WebSocket.js:7605)at(index):34

每当我尝试在客户端的websocket连接上使用send()函数时。 它也给了我错误

与’ws://127.0.0.1:5959 /?.kl = Y’的WebSocket连接失败:WebSocket在建立连接之前关闭。

这是服务器的源代码:

int new_socket; int activity; int i; int sd; int max_sd; int bytes_read; fd_set readfds; int master_socket; noPollConn* new_conn; /*Create no poll context*/ noPollCtx* ctx = nopoll_ctx_new(); noPollConn* conn; char buffer[3000]; /*Create a connection listener at 127.0.0.1 (loopback) on port 5959*/ noPollConn * listener = nopoll_listener_new(ctx, "127.0.0.1","5959"); /*Get the socket of the lister*/ master_socket = nopoll_conn_socket(listener); if(!nopoll_conn_is_ok(listener)) { perror("There was an error creating the listener!\n"); exit(EXIT_FAILURE); } puts("Waiting for connections ..."); while(TRUE){ printf("Start of the while loop\n"); FD_ZERO(&readfds); FD_SET(master_socket, &readfds); max_sd = master_socket; printf("The number of connections is %i\n",cons); for (i = 0 ; i  0) FD_SET(sd,&readfds); if(sd > max_sd) max_sd = sd; } printf("The max fd is %i\n",max_sd); activity = select(max_sd + 1 , &readfds , NULL , NULL , NULL); if ((activity < 0) && (errno!=EINTR)) { puts("select error"); exit(EXIT_FAILURE); } if (FD_ISSET(master_socket, &readfds)){ new_conn = nopoll_conn_accept(ctx,listener); puts("Waiting for the connection to be ready"); nopoll_conn_is_ready(conn); /*Vector is actually a doubly linked list*/ vector_push(&clients,new_conn); cons++; } /*TODO: Implement disconnect*/ for (i = 0; i  %s\n",buffer); } } memset(buffer,0,3000); } 

但是只是一个警告,此代码现在进入无限循环,因为我没有实现与服务器端客户端的断开连接。

 For the client 
 var connection = new WebSocket('ws://127.0.0.1:5959'); connection.onopen = function(){ connection.send("TEST"); alert("Connected"); } connection.onerror = function(error){ console.log('Error detected: ' + error); } connection.onmessage = function (event) { alert(event.data); } connection.close(); 

也许我错过了一些非常重要的事情? 我经历了很多教程,我似乎无法弄清楚问题是什么。 任何帮助是极大的赞赏! 在.onopen()函数中调用.send()导致错误:

与’ws://127.0.0.1:5959 /?.kl = Y’的WebSocket连接失败:WebSocket在建立连接之前关闭。 UPDATE
错误发生在服务器端。 它可能与我处理连接有关,就好像它在C代码中的某些方面是一个套接字。

如果服务器上没有记录错误,则可能会在open事件发生之前调用.send() 。 在open事件处理程序中调用.send() 。 否则,问题出在服务器上。

 const socket = new WebSocket("ws://echo.websocket.org/"); socket.onopen = function(e) { socket.send("WebSocket rocks"); console.log("self.socket event.type:", e.type); }; socket.onmessage = function(e) { console.log(e.data); }; socket.onerror = function(e) { console.log("self.socket error", e); }; socket.onclose = function(e) { console.log("self.socket event.type", e.type); }; 

请参阅如何测试使用JavaScript开发的WebSocket

plnkr http://plnkr.co/edit/W8Wgyw0mbxdMkMMe4wg4?p=preview