After reading several webpages about networking, in attempt to trying to understand basic networking, (I’ve never done networking before) I’ve made a few classes that is designed to make somewhat of a simple chat room. The following classes will be posted below:
ChatServer: http://paste.strictfp.com/32591 ((Edited recently)Creating the actual server that waits for people to connect to it, in this case, through port 9045)
ChatSession: http://paste.strictfp.com/32583 (When a client is found, from the server code above, it creates a new session, which just basically reads the messages that are sent by the clients)
ChatClient: http://paste.strictfp.com/32584 (Allows a client to write to the server)
ServerRunner: http://paste.strictfp.com/32585 (Main method for running the server)
ClientRunner: http://paste.strictfp.com/32586 (Main method for running a client, which connects to the server)
I know the code above isn’t the best, considering the fact that I didn’t add any checks to see if the socket/client got disconnected, or something got interrupted. But then again, this was just a practice in order to help me try and grasp the concept of networking.
So these 5 classes together work fine, but I have a question/concern that would be very much appreciated if answered:
How do I send a message from the server to a client?
The reason why I’m asking is this because I want to make a simple multiplayer tic-tac-toe game, in which there will be a server, and 2 clients (both representing players) and basically what I had in mind was that whenever the clients click on buttons, I’d send a message to the server. And then I would send the message back to both clients in order to modify both of their games. And I’m just a little confused about how it works, due to my lack of networking knowledge. I’d appreciate if you didn’t redirect me to another URL, unless very very very simple, because I prefer if people explain it to me in simplest terms. If someone can help me, it’d be very much appreciated.
There are two meanings for the word “server” which can be confusing:
So what you try to do is to turn your server into a client (and the
ChatClientwould become a server).This explains why this seemingly simple task is so hard: Servers aren’t meant to talk to clients out of the blue. Real world example: A clerk from your bank suddenly shows up on your doorstep and tries to sell you something at your home. Odd, isn’t it?
Solutions: