I am trying to make a simple game that goes across a TCP network.
The server does something like this to check for connections, in Server.java:
try { server = new ServerSocket(port); System.out.println('Server started on port ' + port); while (true) { socket = server.accept(); System.out.println('A new player has joined the server.'); new Server(socket).start(); } }
And to make a new client, in Player.java:
socket = new Socket(hostname, port);
Now, this works fine and all, but I need the server to add the instance of the Player to an array list and be able to send all of them certain data. They both have main methods, so one computer can just run the server and have 4 other computers connect to it by running Player.java. If all Player does is create a new socket, how is the Server supposed to interact with each Player?
I’m not sure I understand the question.
The call to accept will produce a different return value for each connecting client (typically representing the client address and port), so you need to store each of them. You can then interact via the sockets, Sun has a pretty good example in its tutorial:
That being said, save yourself a lot of headache and think over the performance you expect from the game. You can save yourself a lot of trouble and easily add reliability and scalability if you use JMS and ActiveMQ for your communications rather than mess around with sockets yourself.
Spend your time writing the game, not doing low-level socket programming, unless you’re trying to learn.