I am implementing a Java project using client-server architecture. My client goes into an infinite loop when connected via socket.
EDIT1: I have changed my client and server programs to minimal, complete and verifiable codes. The issue arises due to having multiple consumers on the same input and output streams (as pointed by the answer below).
Here is my server code:
import java.net.*;
import java.io.*;
class Demo {
int a;
String b;
Demo() {
a = 10;
b = "Sample";
}
}
class Streamsample {
private ServerSocket serverSocket = null;
DataInputStream dis = null;
DataOutputStream dos = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
Streamsample() {
try{
serverSocket = new ServerSocket(3000);
Socket s = serverSocket.accept();
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
System.out.println(dis.readUTF());
Demo d = (Demo)ois.readObject();
System.out.print(d.a + " " + d.b);
dis.close();
dos.close();
ois.close();
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Streamsample ss = new Streamsample();
}
}
Here is my client code:
import java.net.*;
import java.io.*;
class Demo {
int a;
String b;
Demo() {
a = 10;
b = "Sample";
}
}
class Streamclient {
private Socket s = null;
DataInputStream dis = null;
DataOutputStream dos = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
Streamclient() {
try{
s = new Socket("localhost",3000);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
dos.writeUTF("Hello");
Demo d = new Demo();
oos.writeObject(d);
dis.close();
dos.close();
ois.close();
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Streamclient ss = new Streamclient();
}
}
The system I am implementing requires my client to send and receive objects
as well as String
s, int
s etc. I am attempting to use DataInputStream
and DataOutputStream
for String
s,int
s and ObjectInputStream
, ObjectOutputStream
for object
s. My program goes into an infinite loop. So should I use ObjectStream's for passing
Strings,
ints as well and completely omit
DataStream`s or is there a workaround available which will allow both Streams to be used on the same socket?