2011-09-14 21 views
0

當我開機時,TCPServer開始運行,但之後UDPServer不能運行?如果我交換那些總是第一個運行。我怎樣才能開機?如何使TCP和UDP服務器都開始使用?哪裏只有其中一個入門

所有其餘的靴子都很好。我該如何解決這個問題?

/** 
* Boot baby boot 
* @param args 
*/ 
public static void main(String[] args) 
{  
    /* Heavy load - 1 */ 
    new Thread(new Runnable() 
    { 
     public void run() 
     { 
     SwingUtilities.invokeLater(new Runnable() 
     {  
      public void run() 
      {    
       TCPServer tcpserver = null; 
       try { 
        tcpserver = new TCPServer(8888);   
       } 
       catch (IOException e){ 
        e.printStackTrace(System.err); 
       } 
       tcpserver.waitForConnections();    
      } 
     });     
     } 
    }).start(); 

    new Thread(new Runnable() 
    { 
     public void run() 
     { 
     SwingUtilities.invokeLater(new Runnable() 
     {  
      public void run() 
      {    
       UDPServer udpserver = null; 
       try { 
        udpserver = new UDPServer(8889);   
       } 
       catch (IOException e){ 
        e.printStackTrace(System.err); 
       } 
       udpserver.waitForConnections(); 
      } 
     });     
     } 
    }).start();   

    /* Heavy load - 2 */      
    try {                  
     Game3Dstart();   
    } catch (Exception ex) { 

    } 

    /* Finally */ 
    j = new main(); 
    j.setVisible(true);     
} 
+0

不好,爲什麼這個世界上鞋跟/是開放裹成的invokeLater()連接東西,找閃屏,打開連接裹進了Runnable#線,如果這樣做,然後換'j.setVisible(真);'到invokeAndWait(),它 – mKorbel

回答

4

這是因爲waitForConnections被阻止。你需要在不同的線程中啓動它們的異步。

new Thread(new Runnable(){ 
    public void run(){ 
     TCPServer tcpserver = null; 
     try { 
      tcpserver = new TCPServer(8888);    
     } 
     catch (IOException e){ 
      e.printStackTrace(System.err); 
     } 
     tcpserver.waitForConnections(); 
    } 
}).start(); 

new Thread(new Runnable(){ 
    public void run(){ 
     UDPServer udpserver = null; 
     try { 
      udpserver = new UDPServer(8889); 
     } 
     catch (IOException e){ 
      e.printStackTrace(System.err); 
     } 
     udpserver.waitForConnections(); 
    } 
}).start(); 
+0

非常好。它驚人的作品謝謝。 – YumYumYum

2

UDP和TCP服務器在不同的線程:

/* Heavy load - 1 */ 
SwingUtilities.invokeLater(new Runnable() 
{  
    public void run() 
    {    
     TCPServer tcpserver = null; 
     try { 
      tcpserver = new TCPServer(8888);    
     } 
     catch (IOException e){ 
      e.printStackTrace(System.err); 
     } 
     tcpserver.waitForConnections();   

     catch (IOException e){ 
      e.printStackTrace(System.err); 
     } 

    } 
} 
/* Heavy load - 1 */ 
SwingUtilities.invokeLater(new Runnable() 
{  
    public void run() 
    {    

     UDPServer udpserver = null; 
     try { 
      udpserver = new UDPServer(8889); 

     } 
     catch (IOException e){ 
      e.printStackTrace(System.err); 
     } 
     udpserver.waitForConnections(); 
    } 
}); 

);

+0

我試過你的方法,但仍然只有1作品。但最後通過刪除SwingUtilities ...並簡單地添加一個線程很好地工作。謝謝!! – YumYumYum

相關問題