2017-09-18 92 views
2

我開發了一個簡單的視頻遊戲,我想用多人功能使用websockets進行更新。我想要有兩個版本的遊戲。第一個用作服務器,另一個用作客戶端。我想從服務器初始化遊戲並等待客戶端的反應。我的第一個問題:是否有可能在同一臺機器上運行服務器和客戶端(給出相同的IP作爲輸入)?其次我使用,以便將下面的代碼創建一個從服務器端的插口:與java中的服務器和客戶端websockets進行通信

try { 
     serverSocket = new ServerSocket(10007); 
    } 
    catch (IOException e) 
    { 
     System.err.println("Could not listen on port: 10007."); 
     System.exit(1); 
    } 

    System.out.println ("Waiting for connection....."); 

    try { 
     clientSocket = serverSocket.accept(); 
    } 
    catch (IOException e) 
    { 
     System.err.println("Accept failed."); 
     System.exit(1); 
    } 
    System.out.println ("Connection successful"); 

當我試圖從客戶端連接,似乎整個事情它不工作,因爲我收到消息waiting for connection... 。我的代碼連接客戶端如下:

String serverHostname = new String("ip"); 

    if (args.length > 0) 
     serverHostname = args[0]; 
    System.out.println("Attemping to connect to host " + 
      serverHostname + " on port 10007."); 

    Socket echoSocket = null; 
    PrintWriter out = null; 
    BufferedReader in = null; 

    try { 
     echoSocket = new Socket(serverHostname, 10007); 
     out = new PrintWriter(echoSocket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(
       echoSocket.getInputStream())); 
    } catch (UnknownHostException e) { 
     System.err.println("Don't know about host: " + serverHostname); 
     System.exit(1); 
    } catch (IOException e) { 
     System.err.println("Couldn't get I/O for " 
       + "the connection to: " + serverHostname); 
     System.exit(1); 
    } 

這是什麼問題在這裏?

+0

你的意思是[WebSocket](https://tools.ietf.org/html/rfc6455)? –

回答

1

你的服務器端代碼沒問題。這裏只需要注意一點,ServerSocket.accept();方法是ablocking調用,這意味着程序執行將暫停,直到客戶端連接到它。

其次,我可以從你的客戶端代碼如下

if (args.length > 0) 
    serverHostname = args[0]; 

args[0]可能不是一個IP地址,我不是太肯定java命令行應用程序的行爲,但在C++中的第一行看到的問題例如,在正確的上下文中的args [0]總是程序可執行文件的絕對路徑。這可能也是在Java中的情況。 所以你可能會傳遞一個IP地址,但實際上會傳入args[1]

相關問題