所以,我有一个不公开的线程类,因为它放在服务器类中。我有一个与clientSocket
类交互的clientWindow
类。 clientWindow
类接受输入并将其发送到服务器。没有连接问题。 clientWindow
类通过调用将变量(getString(String s)
)设置为该字符串clientIn
的方法(s
)将String传递给服务器。我有它,所以线程类syso内部的方法是一条消息:"clientIn was set by the client. " + clientIn"
。请注意,clientIn
是公开的和静态的。当执行线程类的run方法时,它运行以下代码:
ClientWindow cw = new ClientWindow();
int maxClientsCount = this.maxClientsCount;
//maxClientsCount is just 15.
clientThread[] threads = this.threads;
try {
/*
* Create input and output streams for this client.
*/
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
//getting the player's name. (unincluded code)
os.println("Welcome " + name);
//sets the clientname to the name of the client which is stored in
//threads.(unincluded code)
//this for loop sends the message to all clients.
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null) {
threads[i].os.println("new user " + name + " entered");
}
}
//waits until there are at least 2 players connected until the game can
//start (unincluded code)
ZombieDiceServer.waitStart();
该方法只是使得启动按钮启用并且while循环等待直到管理员按下该按钮以启动游戏。在此期间,玩家仍可以连接。
//(unincluded game code)
synchronized (this) {
String restart = "";
System.out.println("clientIn: " + clientIn);
while (true) {
restart = clientIn;
if (!clientIn.isEmpty()) {
//the following for loop prints out the given string to all
//threads/clients.
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null) {
threads[i].os.println("<" + name + "> " + clientIn);
}
}
}
//(unnecessary code)
}
}
getString(String s)
方法如下:
public static void getString(String s) {
clientIn = s;
System.out.println("clientIn was set by the client. " + clientIn);
}
ClientSocket
控制台输出:
responseLine: Enter your name.
responseLine: *** A new user M entered the chat room !!! ***
responseLine: Welcome B to Zombie Dice.
clientIn was set by the client. B
responseLine: To leave, enter "/quit" in a new line.
responseLine: Please wait while other players join!
responseLine: *** A new user B entered the chat room !!! ***
clientIn was set by the client. hi
ZombieDiceServer
控制台输出:
clientIn was called.
clientIn at start:
clientIn was called.
clientIn at start:
clientIn:
clientIn:
请注意,在线程中调用该方法的客户端会记住它,但不会记住它被发送到的线程。为什么?!