I am writing a general Client-Server socket program where the client sends commands to the Server, which executes it and sends the result to the Client.
However if there is an error while executing a command, I want to be able to inform the Client of an error. I know I could send the String "ERROR" or maybe something like -1 etc, but these could also be part of the command output. Is there any better way of sending an error or an exception over a socket.
My Server is in Java and Client is in Python
views:
36answers:
2Typically when doing client-server communication you need to establish some kind of protocol. One very simple protocol is to send the String "COMMAND" before you send any commands and the String "ERROR" before you send any errors. This doubles the number of Strings you have to send but gives more flexibility.
There are also a number of more sophisticated protocols already developed. Rather than sending Strings you could construct a Request object which you then serialize and send to the client. The client can then reconstruct the Request object and perform the request whether it's performing an error or running a command.
You're already (necessarily) establishing some format or protocol whereby strings are being sent back and forth -- either you're somehow terminating each string, or sending its length first, or the like. (TCP is intrinsically just a stream so without such a protocol there would be no way the recipient could possibly know when the command or output is finished!-)
So, whatever approach you're using to delimiting strings, just make it so the results sent back from server to client are two strings each and every time: one being the error description (empty if no error), the other being the commands's results (empty if no results). That's going to be trivial both to send and receive/parse, and have minimal overhead (sending an empty string should be as simple as sending just a terminator or a length of 0).