1

I'm creating a simple chat in Java, and it works. I just have a problem when a client close the connection, because it continue to appear online. This is because there's no a way to know when a stream is closed.

I searched on google and any solution has not resolved my problem, so I want to send a boolean each 300ms and, if I don't receive any answer or I get an error, I can close the connection server side.

The problem is that there's a conflict in the stream, I can't know if I'm reading a boolean or a text, so sometimes my CheckConnection class try to read a string and my SocketHandler class try to read a boolean, and I receive an error. I use the class ObjectInputStream and ObjectOutputStream to read and write into the stream.

It's my first server application and I don't know very much about it, I don't know if it's possible open more than one stream or if there are other solutions, so I'm asking you. What may I do?

PS: I tried to create a PrintStream and execute the checkError() method, but it returns always false, even if I close explicitly all the streams client side. Thank you.

1
  • its probably good idea to show some codes, I have no idea how you did this
    – nafas
    May 5, 2015 at 15:15

1 Answer 1

1

I suggest you use text as this is simpler to work with to start with.

  • treat any message as a heartbeat. If you get data, the connection is still good.
  • treat a heartbeat as a string and chat as a string. it's all a String so you don't need to worry about what it is.
  • check a stream is open by attempting to read from it and expecting you will get something within a timeout period.

You can use BufferedReader, or Scanner to reads the text. You can user BufferedWriter to write the text.

In your string you can create a simpler protocol like this.

say [to-whom] [message ...]

for the heartbeat you can have

hb

or

heartbeat

or

say nobody hi

You might add commands like

login [user] [password]

and

kthxbye

To decode the message, look at the first word and you know it's purpose and then read the second word for say and the rest of the string is the message.

To test the protocol, you can telnet to the port and type in stuff to the server directly. You don't even need to write a client to start with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.