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.
I suggest you use text as this is simpler to work with to start with.
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.