在socket io中,一个用户连接创建了数十个"加入空间"?

时间:2017-02-09 23:00:35

标签: node.js express socket.io

我在linux上有一个nodejs socket.io应用程序连接到运行socket-io-client的客户端。

nosejs服务器是:

  • node v6.7.0
  • express 4.10.8
  • socket.io 1.4.5

java方面正在使用maven:

  <dependency>
     <groupId>io.socket</groupId>
     <artifactId>socket.io-client</artifactId>
     <version>0.8.3</version>
  </dependency>

我只是从socket.io 0.9迁移,所以我只有一个用户连接到nodejs套接字服务器。

在某些情况下,我有一个奇怪的现象是这一个连接创建了几十个连接

socket.io:socket socket connected - writing packet +106ms
socket.io:socket joining room /#q-brvq0-lMhLKY6tAAAR +0ms
socket.io:socket joined room /#q-brvq0-lMhLKY6tAAAR +0ms
socket.io:socket socket connected - writing packet +46ms
socket.io:socket joining room /#p-_dEpC_2IJoiVtFAAAS +0ms
socket.io:socket joined room /#p-_dEpC_2IJoiVtFAAAS +0ms
socket.io:socket socket connected - writing packet +4ms
socket.io:socket joining room /#9Ha8CuQh6Vw3OROuAAAT +0ms
socket.io:socket joined room /#9Ha8CuQh6Vw3OROuAAAT +0ms
socket.io:socket socket connected - writing packet +192ms
socket.io:socket joining room /#qu1Hhixulei3fDV7AAAU +0ms
socket.io:socket joined room /#qu1Hhixulei3fDV7AAAU +0ms
socket.io:socket socket connected - writing packet +24ms
socket.io:socket joining room /#0Jd2FY5rY-_Rfps6AAAV +0ms
socket.io:socket joined room /#0Jd2FY5rY-_Rfps6AAAV +0ms
socket.io:socket socket connected - writing packet +122ms
socket.io:socket joining room /#BCgabXA28IBHV94NAAAW +0ms
socket.io:socket joined room /#BCgabXA28IBHV94NAAAW +0ms
socket.io:socket socket connected - writing packet +19ms
socket.io:socket joining room /#ibtuQc60nb7kExHvAAAX +1ms

从java客户端,这是创建连接的代码:

        try {
             System.out.println("socket phy create");
            socket = IO.socket(domain+":"+port);
        } catch (URISyntaxException ex) {
            System.out.println("socket URISyntaxException");
        }

95%的时间它只创建了一个&#34; socket connect&#34;和5%它创建了几十个。有什么问题或者您可以建议一种调试方法吗?

1 个答案:

答案 0 :(得分:0)

问题在于系统实施..

在我调试时,我有时会关闭套接字服务器(为了更改一些代码)。在客户端,我每5秒进行一次重新连接检查。此方法每次都调用createNodeConnection。最后我重新加载套接字服务器,所有这些连接立即连接。

修复是将'套接字创建'与'套接字连接'分开(并在重新连接方法中使用'套接字连接')

public void createNodeConnection() {
        try {
            socket = IO.socket(domain+":"+port);
        } catch (URISyntaxException ex) {
            System.out.println("socket URISyntaxException");
        }

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
          @Override
          public void call(Object... args) {...//handle code..}

        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

          @Override
          public void call(Object... args) {...//handle code..}

        }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {...//handle code..};
        });            

        socketConnection();
};


public void socketConnection() {
         socket.connect();            

}