[英]Exception in “helloworld” server and client program in socket programming
[英]Send stream of Data from client program (running in VM) to server program(on Host OS) using socket programming in Java
客戶端套接字程序(在Windows VM中)根據以下代碼生成1到10的整數
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
問題是,當我使用while循環並不使用循環而接收第一個值(即0)時,我正在接收的輸出為-1。
但是,我能夠從客戶端向服務器發送單個值,但是如何從客戶端發送值流並將其打印在服務器端。
歡迎建議
socket.isConnected()
不能為假。 input.ready()
並不是測試流的末尾,消息的末尾,傳輸的末尾或任何真正有用的測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.