Using ObjectInputStream and ObjectOutputStream between client and server process - java

I develop a client-server java application and I used ObjectOutputStream and ObjectInputStream to send and receive data between client and server process. I need to send Array or object or primitive data
but the problem appears when I use ObjectOutputStream and ObjectInputStream to send and receive primitive values ( writeDouble(), readDouble(), writeUTF(), readUTF() ) . the program suspended and stopped working. why, what is the problem?
these are a fragments of my program
// client program
ObjectOutputStream toServer;
ObjectInputStream fromServer;
// Establish connection with the server
Socket socket = new Socket(host, 7000);
// Create an output stream to the server
toServer = new ObjectOutputStream(socket.getOutputStream());
fromServer = new ObjectInputStream(socket.getInputStream());
double num1 = Double.parseDouble(jtf1.getText().trim());
double num2 = Double.parseDouble(jtf2.getText().trim());
try {
toServer.writeUTF("multiply");
toServer.writeDouble(num1);
toServer.writeDouble(num2);
double result = fromServer.readDouble();
res.setText(String.valueOf(result));
} catch (IOException ex) {
System.err.println(ex);
}
// server program
private ObjectOutputStream outputToClient;
private ObjectInputStream inputFromClient;
// Create a server socket
ServerSocket serverSocket = new ServerSocket(7000);
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
System.out.println("connect ");
outputToClient = new ObjectOutputStream(socket.getOutputStream());
// Create an input stream from the socket
inputFromClient =
new ObjectInputStream(socket.getInputStream());
while(true) {
// Read from input
String command = inputFromClient.readUTF();
System.out.println("receive command");
checkRequest(command);
}
// Write to the file
//outputToFile.writeObject(object);
}
public void checkRequest(String cmd){
//Object o = null;
try{
if(cmd.equals(MULTIBLY)){
double x = inputFromClient.readDouble();
double y = inputFromClient.readDouble();
double result = x*y;
outputToClient.writeDouble(result);
System.out.println("send result");
}else if (cmd.equals(DIVIDE)){
int x = inputFromClient.readInt();
int result = 1000/x;
outputToClient.writeDouble(result);
}
} catch(IOException io){
}
}
when I change ObjectOutputstream and ObjectInputStream to DataOutputStream
and DataInputStream every thing goes correctly !

You must call flush() on the stream on the client side to actually send the data (if the socket's buffer is not full).
You see your program hanging because the client does not send the data, and the server is blocking, waiting for the data that will never come.

Related

the buffer in server doesn't read the value that client sent

The client sends data (string) to the server, and the server must read it, but in my case the server didn't read the data (value) that the client sent, and I didn't know where is the problem exactly, because normally the steps to read data are all correct in the server side
Client side:
Socket socket = new Socket(address, authenticationServerPort);
username = username + "\n"; // to send username through socket without
String h=getUserInput();
// waiting
// Send the message to the server
// send public key
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println(h);
bw.write(h);
bw.flush();
System.out.println("Message sent to the Authentication server : "+ h);
Server side:
Socket clientSocket = null;
try {
System.out.println("Server Running");
int serverPort = 8029; // the server port we are using
ServerSocket listenSocket = new ServerSocket(serverPort);
List<BlockChain> resultList = new ArrayList<BlockChain>();
while (true) {
clientSocket = listenSocket.accept();
InputStream is = clientSocket.getInputStream();
System.out.println(is);
InputStreamReader isr = new InputStreamReader(is);
System.out.println(isr);
BufferedReader br = new BufferedReader(isr);
String request = br.readLine();
System.out.println("the msg receving from client is : "+request);
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
if (clientSocket != null) {
clientSocket.close();
}
}
catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
}
Someone tell me where is the problem exactly.

How to receive an object on a socketServer in java

I want to send an object(array) from a client to a server. I use the ObjectInputStream and the ObjectOutputStream. However, this invokes an error, that these methods are not defined in serverSocket class.
How do I resolve the situation ??`
public int[] readResponse() throws IOException, ClassNotFoundException{
int[] x = new int[5];
ObjectOutputStream cO = new ObjectOutputStream(serverSocket.getOutputStream()); //here is the error
ObjectInputStream cI = new ObjectInputStream(serverSocket.getInputStream()); // here is the error
cO.writeObject(x);
x = (int[]) cI.readObject();
for (int i = 0; i < 5; i++){
System.out.println(x[i]);
}
return x;
}
A java.net.ServerSocket is not meant to be used for actual input and output; it is a socket for listening on the server to incoming connection requests which are accepted, resulting in a java.net.Socket which is then the one for reading and writing.
Socket socket = serverSocket.accept();
ObjectInputStream cI =
new ObjectInputStream(socket.getInputStream());
On the client side, a java.net.Socket is created by calling the constructor and connected, via an address, to the client.
Socket socket = new Socket( address, port );
ObjectOutputStream cO =
new ObjectOutputStream(socket.getOutputStream());

Java socket, client hangs when get input from server output

i have a socket in client that connects to an server to send and receive String, uses writeUTF() and readUTF() to read and write to socket, when i write a string from client to socket and read them on server then it's work. But when server receive string from socket and write "flag" to socket to read them on client then client hang at read line. Here is my code.
Server
public void run(){
DataInputStream input = null;
try{
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
while((true)&&(this.active)){
String receive = input.readUTF();
String[] str = receive.split("#");
if (str[0].equals("get_list")){
output.writeUTF("flag");
}
}
}catch(IOException ex){
}
Client
public void run(){
DataOutputStream output = null;
try{
output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
output.writeUTF("get_list#");
String receive = input.readUTF(); //Hang at this line
System.out.println(receive);
} catch (IOException ex) {
}

Send string to client upon command JAVA

So I am trying to have a sever sit and listen waiting for a connection from a client. The client sends over some string and the sever does some action based on whats received. Now what I would like to happen is the client sends over some command asking for data back and have the server get what it needs to and send the string back.
Not a big deal right? Well for some reason I can't get it working, my best guess is that its not closing the socket properly. I can't figure out why it wouldn't or what I am doing wrong.
Client
String data = "";
DataOutputStream outToServer = null;
BufferedReader input;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("GETDATA");
outToServer.flush();
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
data = input.readLine();
Log.d("ANSWER: ", data);
input.close();
} catch (IOException e) {
Log.d("Error: ", e.toString());
}
Server
ServerSocket listeningSocket = new ServerSocket(9008);
BufferedReader fromClient ;
PrintStream os;
while(true) {
Socket clientSocket = listeningSocket.accept();
ServerConnection clientConnection = new ServerConnection(clientSocket);
os = new PrintStream(clientSocket.getOutputStream());
fromClient= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(fromClient.readLine().equals("GETDATA")){
os.println("DATA");
os.flush();
clientSocket.wait();
clientSocket.close();
}
else{
clientConnection.run();
}
}
Any ideas?
here is your error
outToServer.writeBytes("GETDATA");
the right code is
outToServer.writeBytes("GETDATA\n");
as your using readline you should send a full line with line break

Debugging a socket communication program

I have 2 classes (Client and Server) used to implement simple communication in my application. My code is shown below:
Server:
public class Server {
public static void main(String[] ar) {
int port = 1025; // just a random port. make sure you enter something between 1025 and 65535.
try {
ServerSocket ss = new ServerSocket(port); // create a server socket and bind it to the above port number.
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("enter meter id ");
String line = null;
while (true) {
line = in.readUTF(); // wait for the client to send a line of text.
System.out.println("client send me this id number " + line);
line = keyboard.readLine();
out.writeUTF(line);
out.flush();
//line = in.readUTF();
System.out.println("Waiting for the next line...");
System.out.println();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
Client:
public class Client {
public static void main(String[] ar) {
int serverPort = 1025;
String address = "localhost";
try {
InetAddress ipAddress = InetAddress.getByName(address); // create an object that represents the above IP address.
System.out.println(" IP address " + address + " and port "
+ serverPort);
Socket socket = new Socket(ipAddress, serverPort); // create a socket with the server's IP address and server's port.
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
// Create a stream to read from the keyboard.
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
System.out.println("ClientConnected.");
System.out.println("enter meter id");
while (true) {
line = keyboard.readLine(); // wait for the user to type in something and press enter.
System.out.println("Sending this number to the server...");
out.writeUTF(line); // send the above line to the server.
out.flush(); // flush the stream to ensure that the data reaches the other end.
line = in.readUTF(); // wait for the server to send a line of text.
System.out
.println("The server was very polite. It sent me this : "
+ line);
System.out.println();
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
My problem is that while testing the program I do get communication between the client and server, but while debugging, with a break point on the out.flush line in Server.java, it does not go to the intended destination. This intended destination being the line line = in.readUTF(); of Client.java. Can anyone help me to solve this?
It is good practice to open the OutputStreams before the InputStreams, on your sockets, as said in this question.
This question also clarifies that.
What I suspect here is your client and server are running in two different JVM processes and java debugger cannot debug two JVM at the same time.

Categories