2017-08-16 62 views
0

客戶端插座計劃(在windows VM)生成按照下面的代碼從1到10整數使用套接字編程從客戶端程序發送數據的流(在VM中運行)到服務器程序(在主機OS)中的Java

public class ClientSocket { 

    public static void main(String[] args) 

    { 

try{ 
    InetAddress inetAddress = InetAddress.getLocalHost(); 
    String clientIP = inetAddress.getHostAddress(); 
    System.out.println("Client IP address " + clientIP); 

    Integer dataSendingPort ; 
    dataSendingPort = 6999 ; 

    Socket socket = new Socket("192.168.0.32",dataSendingPort); 
    String WelcomeMessage = " hello server from " + clientIP ; 


BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 

if(socket.isConnected()){ 
    System.out.println("connection was successful"); 
} 
else{ 
    System.out.println("Error- connection was not successful"); 
} 


for (int x= 0 ; x< 10 ; x++){ 
    bufferedWriter.write(x); 
    bufferedWriter.flush(); 
} 

    bufferedWriter.close(); 
} 
catch (IOException e){ 
    System.out.println(e); 
}// catch 
     finally{ 

    System.out.println("closing connection"); 

} 

    } // main 

} // class 

我的服務器套接字程序在Mac OS上運行的主機,其代碼如下所示

public class MyServer { 

     public static void main(String[] args) throws Exception { 


      try { 
// get input data by connecting to the socket 


       InetAddress inetAddress = InetAddress.getLocalHost(); 
       String ServerIP = inetAddress.getHostAddress(); 

       System.out.println("\n server IP address = " + ServerIP); 

       Integer ListeningPort ; 
       ListeningPort = 6999 ; 

       ServerSocket serverSocket = new ServerSocket(ListeningPort); 

       System.out.println("server is receiving data on port # "+ ListeningPort +"\n"); 

       // waiting for connection form client 

       Socket socket = serverSocket.accept(); 


       if(socket.isConnected()){ 

        System.out.println("Connection was successful"); 
       } 
       else { 
        System.out.println("connection was not successful"); 
       } 



       BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

    Integer s = 0 ; 

     while ((s = input.read()) >= 0){ 

      System.out.println(input.read()); 
     } 
      } //try 

      catch (IOException e) 
      { 
       System.out.println(e); 

      } // catch 


     } //main 
    } //socket class 

的問題是輸出我收到爲-1,當我用while循環和接收第一個值,即0而不使用循環。

但是,我能夠從客戶端發送一個值服務器,但 我怎樣才能從客戶端發送價值觀的流並將其打印在服務器端 。

建議是最歡迎

回答

1
  • -1表示流的末尾。
  • 關閉股票的輸入或輸出流會關閉套接字。
  • socket.isConnected()在您測試時不可能是錯誤的。
  • input.ready()不是測試結束的流,或消息的結束,或傳輸的結束,或真正有用的東西。
  • 請勿沖洗內部循環。
相關問題