Question

I am using TCP Sockets and I am a beginner in Java and Sockets too. The scenario is that the client,depending on server 's answer, may send either int or a string. I need to save the output stream of the client, in a variable on the server 's side, so i can use it in if statements and so on. But how could I do this when i don t know if the stream sent is an integer or a string?

I have made a very simple example, because my code is huge and messy and i don t want to make it more complex

Client Side:

serverSentence=inFromServer.readLine();   
if (serverSentence.equals("Hello"))
     {
     anInt=readUserInput.nextInt(); 
     outToServer.write(anInt);
     }
else 
     {
     outToServer.writeBytes("Hello word!"+'\n');
     }

So how I could do this, I mean saving in a variable the Client 's output stream, in the Server 's side (or the opossite), so I could use it in loops and ifs?

Was it helpful?

Solution

Use Object. A reference typed as an Object may refer to Integer or String. Another story is of course deserializing the incoming data as either. If the problem has to do with not knowing how to interpret serialized data, include some sort of flag to indicate what the data is.

OTHER TIPS

You should design your protocol of communication between server and client in such a way that server would be able to read some information (you could call it standard header), and based on that would know how to interpret the remaining bytes sent by the client.

And then you'll know how to read the data from client, and where to store it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top