2017-08-19 66 views
0

我正在編寫一個服務器客戶端程序。它就像一個簡單的控制檯聊天室。我使用服務器線程來處理多個客戶端。如果我把Scanner放在客戶端的構造函數中,它會很好用。(這部分是註釋)但是,我想將請求用戶輸入的Scanner部分移動到main。我得到socket close error。我不知道問題是什麼。如何使用send函數發送main中的數據?如何將數據發送到客戶端類以外的服務器

客戶:

public class GameClient { 
private Socket socket; 
private String serverIP; 
private OutputStreamWriter writer; 
private BufferedReader reader; 

public GameClient(String host){ 
    this.serverIP = host; 

    try{ 
     //Connect to server 
     socket = new Socket(InetAddress.getByName(serverIP), 1234); 
     writer = new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8"); 
     reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8")); 
     //Start a new thread for reading from server 
     new Thread(new GameClientReader(socket)).start(); 

     Scanner scanner = new Scanner(System.in); 
     System.out.println("Write something: "); 
     String str = ""; 
//   while((str = scanner.nextLine()) != null){ 
//    writer.write(str); 
//    writer.write('\n'); 
//    writer.flush(); 
//    System.out.println("Write something: "); 
//   } 

    }catch(IOException e){ 
     System.out.println("Client failed to connect!"); 
     e.printStackTrace(); 
    }finally{ 
     try { 
      socket.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 


public void send(JSONObject json){ 
    try{ 
     String message = json.toJSONString(); 
     writer.write(message); 
     writer.write('\n'); 
     writer.flush(); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
} 

public void send(String msg){ 
    try { 
     writer.write(msg); 
     writer.flush(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public static void main(String args[]){ 
    GameClient client = new GameClient("127.0.0.1"); 

    Scanner scanner = new Scanner(System.in); 
    System.out.println("Write something: "); 
    String str = ""; 
    while((str = scanner.nextLine()) != null){ 
     client.send(str); 
     System.out.println("Write something: "); 
    } 

} 
} 
+0

例如有沒有這樣的錯誤爲「套接字關閉錯誤」 。你的問題與你的頭銜無關。不清楚你在問什麼。 – EJP

回答

0

您關閉SocketGameClient構造finally塊,然後調用方法send它調用writer.write(msg);使用的Socket

相關問題