I'm a bit confused on how I can send a message to everyone that is connected to my socket
for example, I'm making a chat, 5 people join my chat and one person says "Hello" that message is then send to the server and the server recives the "Hello" message.
Now I need the server to send the "Hello" message to everyone who's connected to port 202 "the open socket"
Thanks a lot people, appriciate every bit of help.
Your server will get a Socket object for each time the server has called ServerSocket.accept() -- one for each client. You should just save all these in a Collection of some kind, and then periodically send updates to all of them using a plain old for-loop.
Recall? Not sure what you mean. Someplace you've got a loop like this, right?
Just add an ArrayList as a member to the class where this appears, and then right below the "accept" call, add the Socket to the ArrayList. Then whenever you need to send something to every client, just loop over this ArrayList.
Joined: May 09, 2009
I've got it to add the clients to the array list but not sure how to make java loop over every client in the array list then stop
author and iconoclast
If you save the sockets in a list, then you still need to worry about the IO streams.
A straightforward, but not optimal solution is to create a class that implements runnable.
In the class that calls accept, keep an ArrayList of of objects.
The runnable class takes the socket in the constructor and creates the IO streams. A static arraylist in this class holding all output streams along with a static method to iterate over this list should be created.
Then when a thread gets a message, it calls the static method with the message as the argument. An important issue with this is dealing with concurrent calls to this static method. If 2 threads are in the static method at the same time, weird results can happen. Since all this method does is iterate over the list and call an output method, you can't do much harm to the program.
Using ObjectOutputStream and ObjectInputStream for the IO is a pretty simple method. If you are only dealing with strings using writeUTF() and readUTF() is very straightforward.
For this to work you need to have a basic understanding of Threads and its issues. The basics are not too complex.
If you are really interested in learning network programming in java, I highly recommend this book. It covers IO and threads in great detail and also covers java network programming topics better then anywhere else that I have seen, especially the SSL sections.
A word of advice, if you are interested in doing a lot of network programming, it pays to learn network concepts, especially TCP/UDP/IP and firewalls. Just like regular programming, understanding what is going on "under the hood" will make you a much better programmer, instead of just learning the java API's.
"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra