我以前是通过以下方式完成的。我有一个服务器套接字
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);
}
}
然后在客户端,我有类似这样的东西...
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();
}
客户端可以通过输出流向服务器发送请求,并从输入流中读取服务器数据。
服务器可以接受来自客户端的请求,并在GameController中处理它,还可以使用输出流从服务器发送通知,同样在GameController中执行。
编辑:此外,我应该注意到,我所有的通信都是通过XML完成的,客户端或服务器上的控制器解码XML并执行相关的请求。
希望这有所帮助。对于我来说肯定有效,使我的多人游戏运行良好。