Cannot get ObjectInputStream to work - java

I am currently trying to get my server to create a connection with a client. I have created a thread for each connection but the server is currently not creating the Input Stream. I have tested this by printing out numbers but only 1 and 2 get printed out. Im sure this is just a small problem that im missing.
public class ObjectHandler implements Runnable{
Socket sock;
ObjectInputStream ois;
ObjectOutputStream oops;
InputStream is;
public ObjectHandler(Socket clientSocket) throws IOException {
System.out.println("1");
sock = clientSocket;
is = sock.getInputStream();
System.out.println("2");
ois = new ObjectInputStream(new BufferedInputStream(is));
System.out.println("3");
OutputStream os = sock.getOutputStream();
oops = new ObjectOutputStream(new BufferedOutputStream(os));
outputSockets.add(oops);
}
I have now removed the throws IOException and surrounded the reader with a try catch. After the client has crashed it now prints this error:
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ThreadPool$ObjectHandler.<init>(ThreadPool.java:95)
at ThreadPool.addThread(ThreadPool.java:31)
at ObjectServerTest.go(ObjectServerTest.java:93)
at ObjectServerTest.main(ObjectServerTest.java:124)

When constructing Object streams over sockets, you always need to construct the output stream first and flush it before creating the input stream (due to how the streams are implemented).

Remove BufferedInputStream. You do not need it. It is waiting until 4K bytes are read.
Edit:
remove BufferedOutputStream too.
And make sure that you are flushing the output stream on client side.

This works for me...
ObjectHandler:
public ObjectHandler(Socket clientSocket) throws IOException {
System.out.println("1");
sock = clientSocket;
}
#Override
public void run() {
try {
is = sock.getInputStream();
System.out.println("2");
ois = new ObjectInputStream(new BufferedInputStream(is));
System.out.println("3"+ois.readFloat());
OutputStream os = sock.getOutputStream();
oops = new ObjectOutputStream(new BufferedOutputStream(os));
} catch (IOException e) {
e.printStackTrace();
}
}
Client:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client = new Socket(InetAddress.getByName("localhost"), 8888);
OutputStream os = client.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeFloat(new Float(10.10));
oos.flush();
}

Related

readUTF() returns error after writeObject()

I'm setting up a new server-client system. Here from the client, an object will be sent to the server. And after receiving the object the server will send a string to the client.
Here the server reads the object successfully. But when the clients want to read the string sent by the server it throws EOFException.
client-side
public static void main(String args[]) throws IOException, EOFException {
try (Socket socket = new Socket("localhost", 1254)) {
OutputStream outputStream = socket.getOutputStream();
InputStream s1In;
DataInputStream dis;
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
s1In = socket.getInputStream();
dis = new DataInputStream(s1In);
Frame frame = new Frame();
frame.setData("test");
objectOutputStream.writeObject(frame);
String st = "";
while(dis.available() >0){
st = dis.readUTF();
}
System.out.println(st);
}
dis.close();
s1In.close();
}
}
server-side
public static void main(String args[]) throws IOException, ClassNotFoundException {
ServerSocket s = new ServerSocket(1254);
Socket socket = s.accept();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//input stream
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Frame frame = new Frame();
frame = (Frame) objectInputStream.readObject();
String data = frame.getData();
System.out.println(data);
// Send a string!
DataOutputStream dos = new DataOutputStream (outputStream);
dos.writeUTF("Received");
dos.close();
objectOutputStream.close();
outputStream.close();
objectInputStream.close();
inputStream.close();
socket.close();
}
error at client side
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at computernetworklab.Client.main(Client.java:38)
/home/shahad/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)

Thread cannot read and write streams on the same socket at the same time?

Code with lines commented-out works, code with those lines does not.....why? and how do I fix it? (note: roughly same code running on the other end)
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream);
//ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
//System.out.println( ois.readUTF());
oos.writeUTF("hey");
}
} catch (Exception e) {e.printStackTrace(); }
}
Edit:
Made some code to make it clearer what I'm getting at, yes its a little messy. (regardless of there being two sockets or not it doesn't seem to work):
Server.java (main):
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(6666);
ServerSocket server2 = new ServerSocket(6667);
Socket socket = server.accept();
Socket socket1 = server2.accept();
OutputStream output = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(output);
ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());
while (true) {
System.out.println("server reading");
System.out.println( ois.readUTF());
System.out.println("server writing");
oos.writeUTF("hey");
}
} catch (Exception e) {e.printStackTrace(); }
}
Client.java (main)
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 6666);
Socket socket1 = new Socket("127.0.0.1", 6667);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());
while (true) {
System.out.println("client writing");
oos.writeUTF("yo");
System.out.println("client reading");
System.out.println( ois.readUTF() );
}
}
Output
Server:
server reading
Client:
client writing
client reading
.flush() your output streams. In my examples after writing on the output stream I have:
oos.flush();
I should have always flushed when I wanted to be sure the message was sent.

Is it possible to create more than 1 consumers on InputStream and OutputStream?

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 Strings, ints etc. I am attempting to use DataInputStream and DataOutputStream for Strings,ints and ObjectInputStream, ObjectOutputStream for objects. My program goes into an infinite loop. So should I use ObjectStream's for passingStrings,ints as well and completely omitDataStream`s or is there a workaround available which will allow both Streams to be used on the same socket?
You are consuming the same streams twice - it cannot work by design. You should only have one consumer for each of your streams, e.g.:
TicketBooking.oos = new ObjectOutputStream(s.getOutputStream());
TicketBooking.ois = new ObjectInputStream(s.getInputStream());
Why do you need two consumers for each of your input and output streams?

Java: Send and recive an Object over Socket

I am a student and learning Network Programming and have a some problem.
This is my client:
public class Test2Client_Tranfer_An_Obj {
Socket socket = null;
ObjectOutputStream out;
ObjectInputStream in;
public Test2Client_Tranfer_An_Obj() {
try {
socket = new Socket("localhost", 12345);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
System.out.println("Ready");
System.out.println("" + in.readUTF());
System.out.println("" + in.readUTF());
System.out.println("Recived");
out.writeUTF("hihi");
System.out.println("Sended");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("Client");
Test2Client_Tranfer_An_Obj test = new Test2Client_Tranfer_An_Obj();
}
}
This my Server:
public class Test2Server_Tranfer_An_Obj {
ServerSocket serverSocket;
ObjectOutputStream out;
ObjectInputStream in;
public Test2Server_Tranfer_An_Obj() {
try {
serverSocket = new ServerSocket(12345);
Socket socket = serverSocket.accept();
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
System.out.println("Ready!");
out.writeUTF("huhu");
out.writeUTF("hoho");
System.out.println("Sended");
String s = in.readUTF();
System.out.println("" + s);
System.out.println("Recived");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("Server");
Test2Server_Tranfer_An_Obj demo = new Test2Server_Tranfer_An_Obj();
}
}
But, when i run my program, this result:
Server Console
Server
Ready!
Sended
Client Console
Client Ready
Anybody can tell me why and what i can do?
Thank for reading!
Hope recive you answer
Object Stream is overkill in this case. You are not actually using writeObject/readObject and using DataInputStream and DataOutputStream would do what you want.
In this particular case, an Object Stream is buffered, which means that small writes are buffered until you either flush() or close() the stream to improve performance. As you don't do either, the writeUTF only writes to memory, not the Socket.
c.f. Data Streams are not buffered by default.
In your server after write to the outputstream. you have to add out.flush() to write to socket

Send String from server to client - save it as textfile

I know how to send a file from a server to a client but how do I send a textstring to the client where the client save the string as a file? Should I use PrintWriter for this issue?
This is the code for sending a file from server to client:
Sending files through sockets
What I want to do is to (instead of sending a file), sending a String from the server and let the client receive it and save it as a file.
public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("send.jpg");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}
static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("recv.jpg");
copy(in, out);
out.close();
in.close();
}
static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
client();
}
}
in that case use ObjectOutputStream at server side to write String and use ObjectInputStream at client side to read String coming from server..
so your server() method will look like this..
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
OutputStream out = socket.getOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject("your string here");
oout.close();
}
and client() method will look like this..
static void client() throws IOException, ClassNotFoundException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
ObjectInputStream oin = new ObjectInputStream(in);
String stringFromServer = (String) oin.readObject();
FileWriter writer = new FileWriter("received.txt");
writer.write(stringFromServer);
in.close();
writer.close();
}
also throw ClassNotFoundException in main method.
public static void main(String[] args) throws IOException, ClassNotFoundException {.......}
done...

Categories