我想制作一个有 2 个玩家的游戏。我将使用 udp 服务器和 2 个客户端,我不知道如何将 2 个客户端同时连接到 1 个服务器以及它们将如何通信。我将只使用java。最后鼠标单击将如何与服务器同步
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
服务器
public class Provider {
public ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
String[] torino={"null","null"};
Provider() {}
void run()
{
try {
//1. creating a server socket (8080=port , 2 =number of connections)
providerSocket = new ServerSocket(8080, 2 );
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
// flush= clean the object out
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
try {
//take the message from client
message = (String)in.readObject();
if (torino[0]=="null")
torino[0]=message;
} else if (torino[1]=="null") {
torino[1]=message;
}
}
catch(ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} catch(IOException ioException) {
ioException.printStackTrace();
}
finally {
//4: Closing connection
try {
in.close();
out.close();
providerSocket.close();
} catch(IOException ioException) {
ioException.printStackTrace();
}
}
}
//method to send messages from server to clients
void sendMessage(String msg)
{
try {
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException) {
ioException.printStackTrace();
}
}
//main method
public static void main(String args[])
{
Provider server = new Provider();
while(true) {
server.run();
}
}