Amarjit Singh Amarjit Singh - 1 year ago 61
Java Question

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

public class ClientSocket {

public static void main(String[] args)


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

Integer dataSendingPort ;
dataSendingPort = 6999 ;

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

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

System.out.println("connection was successful");
System.out.println("Error- connection was not successful");

for (int x= 0 ; x< 10 ; x++){

catch (IOException e){
}// catch

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


} // main

} // class

My server socket program is running on Mac OS as Host Machine, whose code is shown below

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();


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 = >= 0){

} //try

catch (IOException e)

} // catch

} //main
} //socket class

The issue is that output I am receiving is -1 when I use while loop and receive first value i.e 0 without using a loop.

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

Suggestions are most welcome

Answer Source
  • -1 means end of stream.
  • Closing the input or output stream of a stock closes the socket.
  • socket.isConnected() cannot possibly be false at the point you are testing it.
  • input.ready() isn't a test for end of stream, or end of message, or end of transmission, or anything useful at all really.
  • Don't flush inside loops.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download