Java won't deserialize object after it is sent through socket stream - java

I'm trying to create application that will send object through local network using Sockets. When i run server and client code in Intellij Idea they work fine, but when i run server code on one pc and client code on another pc i get errors like java.io.StreamCorruptedException: invalid type code: 00 or java.io.StreamCorruptedException: invalid stream header: 6C69656E
byte[] readBuffer = new byte[4096];
int num = inStream.read(readBuffer); //inStream is socket input stream
ByteArrayInputStream bis = new ByteArrayInputStream(readBuffer);
ObjectInput in = new ObjectInputStream(bis);
Object o = in.readObject(); //this line throws error
The thing is that writing and reading object to socket stream works on server (which is on pc where i created project) but reading from input stream on client (another pc where i copied project) throws error.
Can someone help me with this? I searched everywhere for solution but i can't figure out what is problem with serializing, because it works on same pc but won't on another. Is there any way that i can make this pc independent? This also happens when i create jar files and run it on same pc where it works in Intellij Idea.

It can because that client didnt read message fully.
But the real mistake is that you work with TCP socket like a message protocol transport but TCP is a stream protocol so you have to create your own message protocol on top of TCP.
Why it works fine on local system?
Because transport data between client and server happen too fast in local test and maybe in just one frame so all the message transported in just one IO-call but in internet or a network it doesn't work like you think.
There is 2 way to handle this mistake:
1- Pass SocketInputStream directly to ObjectInputStream instance and let it handle read objects.
2- Create a message protocol for example you can put the size of message in 2 or more first bytes. Then you can workd like this :
Read 2(or more) first bytes and detect size of packet.
Create a buffer for this size and read packet bytes.(make sure you read all of packet data from socket . You can use return value of SocketInputStream.read(byte[]) method to calculate it)
Pass the packet to ObjectInputStream and read object !

Related

Java InputStream throwing java.io.StreamCorruptedException

I have a problem that I do not quite understand. I have a server socket and a client socket on two separate machines. Server will constantly sends out data in hex and connected client will read the data stream and do some work.
Most of the traffic is happening in that manner. On a few rare occasions, client will send a bytestring to Server. At this point, I am getting
Java.io.StreamCorruptedException at this line:
ObjectInputStream in = new
ObjectInputStream(socketFromClient.getInputStream());
Exception:
java.io.StreamCorruptedException: invalid stream header: 020001B5
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
at ReadInput.run(ReadInput.java:21)
at java.lang.Thread.run(Thread.java:745)
"020001B5" is exactly the bytestring that client is sending over to server.
I do not understand why I am getting this StreamCorruptedException. My
code logic does not have any "stream header". What is stream header?
I checked javadoc and I could not make out of why this is happening.
Any tip much appreciated.
thanks
-v
Your client is not writing data using ObjectOutputStream: that's why you're seeing this exception. ObjectOutputStream and ObjectInputStream are used for serializing and deserializing Java objects.
Instead of using ObjectInputStream to read data, consider using BufferedReader or a DataInputStream.
See this example for more details.

CorruptedFrame exception , websockets in Netty

I was just playing around the websocket example client and server on netty wiki.
I modified the way server sends data to client.
Suddenly i started getting exception like "io.netty.handler.codec.CorruptedFrameException: bytes are not UTF-8"
This is on client and i am creating frame on server like this :-
ByteBuf buf = Unpooled.buffer();
buf.writeShort(1);
channel.write(new TextWebSocketFrame(buf))
I understand from error that bytebuf must be UTF-8 encoded , even the constructor of TextWebSocketFrame says this.
But i have no clue on why i am getting this error.
Any suggestions ?
You are getting this as you try to send non UTF-8 data. If you want to just send any binary data use a BinaryWebSocketFrame.

Java app cannot communicate with RN-171 wifi module

I'm writing a Java code which have to send some data to an elecronic system and to receive some data from it through wireless. The electronic system is made of PIC32 and RN-171 module. I'm now trying to connect to the RN-171 network and to send and receive some data. Although I can in my java code set up an OutputStream and send some data to the RN-171 properly, I can't set up an InputStream and my app launches the following exception:
java.io.StreamCorruptedException: invalid stream header: 2A48454C
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at TestController.sendParametersToWirelessModule(TestController.java:44)
at TestController.main(TestController.java:30)
The code in my java app, which generates the exception is:
try{
//1. creating a socket to connect to the server
requestSocket = new Socket("1.2.3.4", 2000);
System.out.println("Connected to localhost in port 2004");
//2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
--> in = new ObjectInputStream(requestSocket.getInputStream());
//3: Communicating with the server
sendMessage(message); }
(The arrow indicates the code line which generates exception)
Is there a solution? Could anyone help me please?
Thanks
Use the following code instead:
out = requestSocket.getOutputStream();
in = requestSocket.getInputStream();
ObjectOutputStream/ObjectInputStream are used to serialize/deserialize Java objects. There is also no point in flushing the output stream before writing to it.

Why did parseFrom() function hang using protobuf in java socket?

I just want to create echo server/client using protobuf and java.
I tested with protobuf-java-2.4.1 and jdk1.7.
I wrote echo server code like below
// create server socket and accept for client connection.
// ...
link = servSock.accept();
Person person = Person.parseFrom(link.getInputStream()); // blocking position
person.writeTo(link.getOutputStream());
I think it is not necessary to note Person.proto.
The client code is only send Person object using socket input stream and receive echo Person object.
// socket connect code was omitted.
Person person = Person.newBuilder().setId(1).setName("zotiger").build();
person.writeTo(echoSocket.getOutputStream());
person = Person.parseFrom(echoSocket.getInputStream());
But server was blocked in parseFrom function when the server and client both run.
I found if i use writeDelimitedTo() and parseDelimitedFrom(), then that is ok. I don't understand why the writeTo() and parseFrom() function does not working.
Why did the server blocking in there?
Is it necessary to send some end signal from client side?
The reason you have to use writeDelimitedTo()/parseDelimitedFrom() is that otherwise protocol buffers may have no idea how much data it needs to read from the socket. That presents a problem (I say may because you could of course create a message with only fixed length fields that wouldn't require this ... but protocol buffers has to deal with both cases)
The writeDelimitedTo() method writes the length of the message to the OutputStream then the message itself. Its counterpart parseDelimitedFrom() reads the length, then the message.
You can use writeTo() and pasrseFrom() with streams but only if you want to write/read a single message and are closing the stream after writing. The reader will then get an EOF to indicate the end of the message (also the case when reading from a file that contains only a single message).
Don't write your own Client/Server, ie. RPC solution. There is one here......https://code.google.com/p/protobuf-rpc-pro/ which has some nice features already for java.

to read the packet of bytes on client(client Socket) from server(ServerSocket) using java

i m a new .
i m a java developer(fresher) and currently i m working on BSE project and i m facing problem to read the packet of bytes on the client(client socket) from the server(server socket). if u can help me then please help me.
Thanks in advance
Well, if you want to interact directly with packets, then you need to use a DatagramSocket instead of the regular Socket and ServerSocket.
Then, you should visit this link to see a good tutorial on how to get started with sending and receiving individual packets.
The basic idea is that the Client or Server will block on the recieve() call while it waits for its partner to send a packet using send().
If you aren't interested in the individual packets like you indicated in your question, then you will want to use Socket and ServerSocket. The first step to communicating between the two involves code that will look similar to the following:
//Server
// this call will block until the client tries to connect to the server
Socket cientConn = new ServerSocket(8878).accept();
// now you can use the connection's input and output streams to send data
/******************/
// Client
Socket serverConn = new Socket(addressOfServer, 8878);
// now you can use the connections input and output streams
After you get connections set up, you will have basically 2 read/write loops. One on the client, and one on the server.
while(true) [
// check for data from an input stream
...
// respond with message back
}
You will need a similar loop for the client and the server.

Categories