[英]Send stream of Data from client program (running in VM) to server program(on Host OS) using socket programming in Java
A Client socket Program (in windows VM) generates integer from 1 to 10 as per below code 客户端套接字程序(在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
My server socket program is running on Mac OS as Host Machine, whose code is shown below 我的服务器套接字程序在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
The issue is that output I am receiving is -1 when I use while loop and receive first value ie 0 without using a loop. 问题是,当我使用while循环并不使用循环而接收第一个值(即0)时,我正在接收的输出为-1。
However, I was able to send a single value from client to server, but how can I send Stream of Values from the client and print it on Server Side.
但是,我能够从客户端向服务器发送单个值,但是如何从客户端发送值流并将其打印在服务器端。
Suggestions are most welcome 欢迎建议
socket.isConnected()
cannot possibly be false at the point you are testing it. socket.isConnected()
不能为假。 input.ready()
isn't a test for end of stream, or end of message, or end of transmission, or anything useful at all really. input.ready()
并不是测试流的末尾,消息的末尾,传输的末尾或任何真正有用的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.