我有两个类GameServer
和NetworkThread
。程序从其他地方创建一个套接字,然后将其传递给NetworkThread
的构造函数
我只想拥有2个客户,这两个客户互相交流。 NetworkThread
构造函数中的第一个客户端ID为1,另一个客户端的ID为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游戏,其中第一个客户端告诉一个单词而另一个尝试猜测该单词,但我的主要问题是我无法启动成功连接!
答案 0 :(得分:1)
啊,我明白了。您正在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();
}