I have done this before, as follows. I have a server socket
public Server(int port, int numPlayers) {
game = new PRGameController(numPlayers);
try {
MessageOutput.info("Opening port on " + port);
ServerSocket clientConnectorSocket = new ServerSocket(port);
MessageOutput.info("Listening for connections");
while (!game.isFull()) {
final Socket client = clientConnectorSocket.accept();
MessageOutput.info("Client connected from " + client.getInetAddress());
Runnable runnable = new Runnable() {
public synchronized void run() {
PRGamePlayer player = new PRGamePlayer(client, game);
}
};
new Thread(runnable).start();
}
} catch (IOException io) {
MessageOutput.error("Server Connection Manager Failed...Shutting Down...", io);
System.exit(0);
}
}
Then on the client side I have something like this.
public void connect(String ip) {
try {
comms = new Socket(ip, 12345);
comms.setTcpNoDelay(true);
this.input = new CompressedInputStream(comms.getInputStream());
this.output = new CompressedOutputStream(comms.getOutputStream());
this.connected = true;
startServerResponseThread();
} catch (IOException e) {
ui.displayMessage("Unable to connect to server, please check and try again");
this.connected = false;
}
if (connected) {
String name = ui.getUserInput("Please choose a player name");
sendXML(XMLUtil.getXML(new NameSetAction(name, Server.VERSION)));
}
}
public void startServerResponseThread() {
Runnable runnable = new Runnable() {
public void run () {
try {
while (true) {
processRequest(input.readCompressedString());
}
} catch (SocketException sx) {
MessageOutput.error("Socket closed, user has shutdown the connection, or network has failed");
} catch (IOException ex) {
MessageOutput.error(ex.getMessage(), ex);
} catch (Exception ex) {
MessageOutput.error(ex.getMessage(), ex);
} finally {
(PRClone.this).connected = false;
if (serverListenerThread != null) {
MessageOutput.debug("Shutting down server listener Thread");
}
}
}
};
serverListenerThread = new Thread(runnable);
serverListenerThread.start();
}
The client can send requests to the server through the output stream and read server data from the input stream.
The server can receive requests from the client and process it in the GameController, as well as send notifications from the server using the output stream again to the GameController.
EDIT: In addition, I should note that all my communication is done through XML, and the controller on the client or server decodes the XML and makes the corresponding request.
Hope this helps. This certainly does the job for me and allows my multiplayer games to work well.