我有2个类,分别是GameServer
和NetworkThread
。该程序从其他地方创建一个套接字,然后将其传递给NetworkThread
的构造函数
我只想拥有2个客户,并且这2个彼此交互。 NetworkThread
构造函数中的第一个客户端ID为1,另一个为2。
但是,当我启动第二个客户端的连接时,它将永远不会进入NetworkThread
类。这是我的代码:
NetworkThread类:
public class NetworkThread implements Runnable, ActionListener {
Socket newClient;
String userName;
int id;
Scanner sc = null;
PrintWriter pw = null;
public NetworkThread(Socket newClient, String userName, int id) {
this.userName = userName;
this.newClient = newClient;
this.id = id;
try {
pw = new PrintWriter(newClient.getOutputStream());
sc = new Scanner(newClient.getInputStream());
} catch (IOException e) {
}
ConstructFrame();
if (id == 1)
changeTurnAsAGuesser();
else
startConnectionForSecondPlayer();
}
@Override
public void run() {
}
private void changeTurnAsAGuesser() {
String word;
String passing;
word = JOptionPane.showInputDialog(null, "Enter Word",
"input" + userName, JOptionPane.QUESTION_MESSAGE).toUpperCase();
passing = "~:";
do {
char x = sc.nextLine().charAt(0);
// after some works with ~> passing
pw.println(passing);
pw.flush();
} while (checkWord(word, passing) == false);
//checkWord method returns a boolean
} catch (Exception e) {
}
}
private void startConnectionForSecondPlayer() {
new Thread() {
public void run() {
while (true) {
String taken = sc.nextLine();
jf.setTitle(taken);
}
}
}.start();
}
}
GameServer类:
public class GameServer {
static int i = 0;
ServerSocket gameServer = null;
String userName;
public GameServer(String username) {
this.userName = username;
new Thread() {
public void run() {
try {
gameServer = new ServerSocket(4444);
} catch (IOException e) {
}
while (true) {
try {
i++;
Socket newClient = gameServer.accept();
System.out.println(i);
Thread th = new Thread(new NetworkThread(newClient,
userName, i));
th.start();
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
}.start();
}
}
编辑:我想实现一个Hangman游戏,其中第一个客户说出一个单词,而另一个则尝试猜测这个单词,但是我的主要问题是我无法启动成功的连接!
最佳答案
啊,我明白了。您正在NetworkThread
的构造函数中完成所有工作,而不是run()
方法。在构造函数中,当id == 1
时,它将在与changeTurnAsAGuesser
相同的线程中调用accept
。在返回之前不会进行其他accept
调用。
您需要做的是从构造函数中删除if (id == 1)
代码,并将其移至后台线程调用的run()
方法中:
public NetworkThread(Socket newClient, String userName, int id) {
...
ConstructFrame();
// don't do the interactive work in the constructor
}
@Override
public void run() {
// do it in the background thread
if (id == 1)
changeTurnAsAGuesser();
else
startConnectionForSecondPlayer();
}