2016-03-08 29 views
0

我想爲我創建的二十一點遊戲集成一個服務器與多個客戶端,因此我開始在java中使用服務器進行練習。我創建了一個線程,在運行時強制服務器偵聽輸入並生成輸出。然後我添加了一個功能來停止服務器。但是,服務器會隨機生成正確的輸出,並且有時無法連接。下面是當用戶主機服務器的代碼:Java服務器產生不一致的輸出

st = new ServerThread(); //this is a field of type ServerThread 
st.start(); //this runs the server concurrently as a new thread 

這是因爲當他們關閉服務器的代碼:

st.stopThread(); 

最後,這裏是爲serverThread來源:

public class ServerThread extends Thread { 

private volatile boolean isRunning = true; 
private Socket socket; 
private static final int PORTNUM = 1342; 

@Override 
public void run() { 
    while (isRunning) { //should run only when the 
     try { 
      ServerSocket serverSocket = new ServerSocket(PORTNUM); //uses the same port number, which I made a constant 
      //Reading the an object of type Information from the client 
      socket = serverSocket.accept(); 
      ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream()); 
      ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream()); 
      Information i = (Information) serverInputStream.readObject(); 
      //arbitrarily changes the data stored in the information object to verify connection with server 
      i.setI(100); 
      i.setS("new string"); 
      i.setD(4.4); 
      //sends the modified object back to the client 
      serverOutputStream.writeObject(i); 
      serverInputStream.close(); 
      serverOutputStream.close(); 
      socket.close(); 
     } catch (IOException e) { 
      //System.out.println("IOException"); 
      //e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      //System.out.println("ClassNotFoundException"); 
      //e.printStackTrace(); 
     } finally { 
      try { 
       if (socket != null) { //avoid null pointer if no connections have been established 
        socket.close(); 
       } 
      } catch (IOException ex) { 
       //Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 

} 

public void stopThread() { 
    isRunning = false; 
} 

}

任何關於編輯的建議,使我的代碼正確和一致地執行將是wel來。謝謝。

+1

你不是應該在創建的ServerSocket * *前while循環? –

+0

我接受了您的建議,並將服務器套接字的初始化移至while循環之外。但是,服務器返回的不一致(有時會輸出正確的數據,有時它不會連接) –

+0

作爲輸出您期待什麼,以及您實際看到的輸出是什麼? –

回答

0

我會遠離作爲一個實例變量,即移動socket定義,

while (isRunning) { 
    Socket socket = null; 
    try { 
    ...