I have bothered with TCP / IP Communication many times over the past few days (using Java and C #). I understand how this works, and I can use it. My question is rather a question of code design, how to make it the best and easiest way to make a real connection.
For example, ive Created my own multi-user chat server. I want my message to be able to decide whether to send its Auth request or a new chat message to get the current list of users, etc. Etc.
Ive implemented several methods myself, but I'm not very happy about this, since I think this is a more standard and beautiful way to do this.
My first thought was String with delimiters that are separated, here is an example of my implementation of my post in Java:
//The Object-types im Using clientSocket = new Socket(host, port_number); _toServer = new PrintStream(clientSocket.getOutputStream()); _fromServer = new DataInputStream(clientSocket.getInputStream()); //Example Commands my Client sends to the server _toServer.println("STATUS|"); //Gets the Status if server is online or closed (closed can occur when server runs but chat is disabled) _toServer.println("AUTH|user|pw"); //Sends an auth Request to Server with username and Password _toServer.println("MESSAGE|Hello World|ALL"); //Sends hello World in the Normal Chat to all Users _toServer.println("MESSAGE|Hello World|PRIVATE|foo"); //Sends hello World only to the user "foo" _toServer.println("USERS|GET"); //Request a list of all Connected Users //Example In the Recieved Message Method where all The Server Messages Get Analyzed serverMessage = _fromServer.readLine(); //Reads the Server Messages String action = serverMessage.split("|")[0]; if (action.equals("USERS")) { //Example "USERS|2|foo;bar" String users[] = serverMessage.split("|")[2].split(";"); } if (action.equals("MESSAGE")) { //Example "MESSAGE|Hello World|PRIVATE|foo" if(serverMessage.split("|")[2].equals("ALL") { //Code and else for private.... } } if (serverMessage.equals("STATUS|ONLINE")) { // Code // I leave out //Code and } for the next If statements } if (serverMessage.equals("STATUS|OFFLINE")) { if (serverMessage.equals("AUTH|ACCEPTED")) { if (serverMessage.equals("AUTH|REJECT")) {
Is this the way it is usually done? Ad You See I need to send status codes and objects corresponding to the code. Ive thought about writing data in bytes and implementing a "decoder for each object," for example:
int action = _fromServer.readInt();
Please note that this is a more general design. The question is not only for this chat server example, I think they need a small network console game just for practice.
Is there a better way to do this, or even an API / Framework?
Thanks in advance!
source share