我有 2 个课程,它们是GameServer
和NetworkThread
。该程序从其他地方创建一个套接字,然后将它传递给NetworkThread
's 的构造函数
我只想有 2 个客户端并且这 2 个相互交互。构造函数中第一个客户端的 idNetworkThread
是 1,另一个是 2。但是当我启动第二个客户端的连接时,它永远不会进入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();
}
}
游戏服务器类:
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();
}
}
编辑:我想实现一个刽子手游戏,其中第一个客户说出一个词,另一个尝试猜测那个词,但我的主要问题是我无法开始成功的连接!