我一直在编写客户端-服务器应用程序。我创建了多线程服务器。我想知道如何在服务器和客户端之间进行正确的通信。有两个客户端(2 个游戏玩家)具有唯一的 GUID 号(线程名称相同)。播放器线程正在协同工作。
服务器已在上一步中收到玩家 GUID 号码。服务器线程一直在工作。
我有一个步骤的问题 - 如何提供正确的玩家顺序。我尝试了简单的例子:
服务器 - 正在发送 GUID(字符串): - 首先 - player1, - 其次 - player2。片段:
public class ServerToPlayer implements Runnable //server creates this thread for each player
{
private ObjectOutputStream output;
@Override
public void run()
{
...
while(true)
{
output.writeObject(String.valueOf(localKey1)); //localKey1 - GUID number of Player1
output.writeObject(String.valueOf(localKey2)); //localKey2 - GUID number of Player2
break;
}
}
}
线程播放器类:
public class Player implements Runnable
{
private ObjectOutputStream output;
private ObjectInputStream input;
private static boolean startPlayer = true;
@Override
public void run()
{
Thread.currentThread().setName(String.valueOf(GUIDPlayer)); // GUIDPlayer
// -
// describes
// player in
// server
// ...
while (true)
{
String guidInput = (String) input.readObject(); // guid from server
if (Thread.currentThread().getName().equals(guidInput))
{
synchronized (this)
{
startPlayer = true;
doMovement(); // proper player is doing sth
startPlayer = false;
notify();
}
} else if (!Thread.currentThread().getName().endsWith(guidInput))
{
synchronized (this)
{
while (true)
{
wait();
if (!startPlayer)
{
break;
}
}
}
}
}
}
}
The question is how to provide thread communication to receive in this example:
1. first iteration: class Player receives localKey1 from server (GUID of player1):
- player1 should be executing, and player2 should wait
2. second iteration: change executing player - class Player receives localKey2 from server (GUID of player2):
- player2 should be executing, and player1 should wait.
使用此代码 - player1 正在执行,player2 正在等待并且未被唤醒;所以下一步也是错误的。如何提高同步?
我也尝试以这种方式做到这一点:
if(Thread.currentThread().getName().equals(guidInput))
{
startPlayer = true;
doMovement();
startPlayer = false;
}
else if(!Thread.currentThread().getName().endsWith(guidInput))
{
while(true)
{
Thread.sleep(5000);
if(!startPlayer)
break;
}
}
但是通过这种方式,布尔 startPlayer 不会在 th