2014-02-17 190 views
0

这似乎是一个流行的问题,但即使花费大量时间进行故障排除,我仍然无法找到解决方案。我希望有一个更新的解决方案。KryoNet:连接后立即断开连接

我设置了一个简单的服务器和客户端与KryoNet Java网络库。我的问题是,我的客户端在连接到服务器后立即断开连接。

这里是我的代码:

服务器

public class TheServer extends Listener { 

    static Server server; 
    static final int PORT = 8215; 

    public static void main(String[] args) throws IOException { 
     server = new Server(); 
     server.start(); 
     server.bind(PORT); 
     server.addListener(new TheServer()); 
     System.out.println("server started on " + PORT); 
    } 

    public void connected(Connection c) { 
     System.out.println("connected: " + c.getID()); 
    } 

    public void disconnected(Connection c) { 
     System.out.println("disconnected: " + c.getID()); 
    } 

} 

客户

public class TheClient extends Listener { 

    static Client client; 
    static final String IP = "localhost"; 
    static final int PORT = 8215; 

    public static void main(String[] args) throws IOException { 
     client = new Client(); 
     client.start(); 
     client.connect(5000, IP, PORT); 
     client.addListener(new TheClient()); 
     //client.setKeepAliveTCP(2000); 
    } 

} 

运行TheServer然后TheClient后,我的控制台打印:

server started on 8215 
connected: 1 
disconnected: 1 

请注意,连接和断开连接之间的时间几乎是立即执行,当然小于我设置的连接超时时间。另外请注意,我注释掉了setKeepAliveTCP()方法,因为虽然我不认为这是必要的,但是我插入它来查看它是否可行。

回答

2

再过了些digging around,我发现,在启动客户端:的

new Thread(client).start()

代替

client.start()

解决了这个问题。

“从r122开始,客户端更新线程被设为守护程序线程,导致子进程一完成初始化就关闭。”

+0

有时这并不藏汉工作..然后你所有的registerred类应该对他们有一个空的构造,https://github.com/EsotericSoftware/kryonet/issues/35 – Makerimages

+0

这prefectly工作!谢谢 –