2014-02-17 191 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工作!謝謝 –