2015-12-28 85 views
-1

我有一個多人Java遊戲(四個客戶端和一臺服務器),所有類都在一個單一的文件中,我決定重寫主類,並保持代碼在多個較短的類。一切似乎是好的(沒有語法錯誤或運行時錯誤),從服務器端看起來很好,但不是從客戶端 我決定使用Print語句來獲取該錯誤,似乎客戶端無法工作下面的代碼:多人Java遊戲,分裂問題

public class ServerManager implements Runnable { 


public static BufferedReader in; 

public static PrintWriter out; 


private Socket socket; 

@Override 
public void run() { 
    try 
    { 
     socket = Connection.connectToServer(GameStatus.serverIP, GameStatus.serverPort); 
     if(socket != null) { 
      return; 
     } else { 

     } 

     in = new BufferedReader(new InputStreamReader(
      socket.getInputStream())); 
     out = new PrintWriter(socket.getOutputStream(), true); 

應用的該特定區域中的工作版本,是如下面

BufferedReader in; 
PrintWriter out; 
public static void main(String[] args) { 
.... 
.... 
.... 
private class startClient implements Runnable { 
     private Socket socket; 

     @Override 
     public void run() { 
      try 
      { 
       try { 
        socket = new Socket(serverIP, serverPort); 
       } catch (Exception ex) { 

        return; 
       } 
       in = new BufferedReader(new InputStreamReader(
        socket.getInputStream())); 
       out = new PrintWriter(socket.getOutputStream(), true); 

我的代碼有問題嗎?

回答

0

嗯,我已經把套接字連接的開始,並在類的末尾捕獲異常,只是試了一下,並保持在套接字連接後它的工作。

 try 
    { 
     try{ 
     socket = Connection.connectToServer(GameStatus.serverIP, GameStatus.serverPort); 
     //if(socket != null) { 
      //return; 
     //} else { 

    // } 
     } catch (Exception ex){ 
      JOptionPane.showMessageDialog(null, "Can not connect to server!"); 
      if(ex.toString().trim().equals("java.net.SocketException: Connection reset")) 
      { 
       JOptionPane.showMessageDialog(null, "Server is down!\nThe game will now exit..."); 
       System.exit(0); 
      } 
      //else 
     } 
    //} 

     in = new BufferedReader(new InputStreamReader(
      socket.getInputStream())); 
     out = new PrintWriter(socket.getOutputStream(), true);