Websocket 连接保持过早关闭连接 [英] Websocket connection keeps prematurely closing the connection

查看:79
本文介绍了Websocket 连接保持过早关闭连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I am trying to build a C application which functions as a Websockets Server.There are many related questions on here, but none of them seem to be able to help with the problem. The program is able to initially establish a connection, complete the handshake for the websocket successfully, however, cannot seem to be able to keep the connection open. On the client side, I get the error

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

WebSocket.js:7605 Uncaught Error: Attempt to send message on unopened or closed WebSocket at _8b2.window.WebSocket._8d2.send (WebSocket.js:7605) at (index):34

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

whenever I try to use the send() function on the websocket connection on the client side. And also it gives me the error

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

WebSocket connection to 'ws://127.0.0.1:5959/?.kl=Y' failed: WebSocket is closed before the connection is established.

这里是服务器的源代码:

Here is the source code of the server:

 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 < cons ; i++) {
        sd = nopoll_conn_socket((noPollConn*)vector_get(clients,i));
        if(sd > 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 < cons; i++){
        printf("Checking on user %i\n",i);
        conn = (noPollConn*)vector_get(clients,i);
        sd = nopoll_conn_socket(conn);
        if (FD_ISSET(sd, &readfds)){
            printf("Receiving info from socket no. %d...\n",sd);
            bytes_read = recv(sd,buffer,4000,MSG_DONTWAIT);
            buffer[bytes_read] = '\0';
            printf("Received the msg --> %s\n",buffer);

        }
    }
    memset(buffer,0,3000);
}

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

Just a warning though, this code does go in an infinite loop right now as I have not implemented disconnection from the client on the server side.

For the client
<pre><code>
            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();
</code></pre>

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

Perhaps I am missing something very important? I have gone through many tutorials, and I can't seem to figure out what the issue is. Any help is greatly appreciated! Calling .send() in the .onopen() function results in the error:

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

WebSocket connection to 'ws://127.0.0.1:5959/?.kl=Y' failed: WebSocket is closed before the connection is established. UPDATE
The error is on the server side. It might be related to me handling the connection as though it were a socket in some regards in the C code.

推荐答案

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

If no errors are logged at server, the issue could be call to .send() before open event occurs. Call .send() within open event handler. Else, the issue is at server.

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

这篇关于Websocket 连接保持过早关闭连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆