简体   繁体   English

几秒钟后,Socket.io Java客户端自动断开连接

[英]Socket.io Java client automatically disconnects after a few seconds

I am trying to keep a connection between the server and my java client alive. 我试图保持服务器和Java客户端之间的连接处于活动状态。 This is my code: 这是我的代码:

import io.socket.client.*;
import io.socket.client.IO;
import java.net.URISyntaxException;

public class Main {
    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        IO.Options opts = new IO.Options();
        opts.reconnection = true;
        Socket socket = IO.socket("http://localhost:3000", opts);
        socket.connect();
        socket.on("disconnect", args123 -> System.out.println("disconnect"));
        Thread t = new Thread(new test(socket));
        t.start();
    }
}

class test implements Runnable{
    private Socket socket;
    public test(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(3000);
            socket.emit("test","test");
            System.out.println("test");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

The test event in the thread does not arrive on the server because my client disconnects automatically. 线程中的测试事件未到达服务器,因为我的客户端自动断开连接。

I also tried this option for my server: {transports: ['websocket'], upgrade: false} 我还在服务器上尝试了以下选项:{transports:['websocket'],升级:false}

or setting the ping interval and timeout interval 或设置ping间隔和超时间隔

I believe your server is a "http" server. 我相信您的服务器是“ http”服务器。 So that, you can keep connection alive, but you have to tell this to the server. 这样,您可以保持连接活动,但是必须将此通知服务器。 This is done by request headers. 这是通过请求标头完成的。 So, simply, I would send "Connection: keep-alive" header. 因此,简单地讲,我将发送“ Connection:keep-alive”标头。 Moreover, your code doesn't look like an http implementation. 而且,您的代码看起来不像http实现。 So, first you should start implementing "http" protocol, then send "Connection: keep-alive" header. 因此,首先您应该开始实现“ http”协议,然后发送“ Connection:keep-alive”标头。

Trying to keep a connection alive from client is not enough to keep really it alive. 尝试使客户端保持活动连接还不足以使其真正保持活动状态。 You have to agree with server. 您必须同意服务器。

Check how you can keep alive a http connection on https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Keep-Alive上检查如何保持HTTP连接的活动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM