我正在开展一个项目来实施游戏" Monopoly"在Java中。我目前在客户端代码上设置了一个GUI,将文本输入到聊天框(或发送命令)到服务器。
我的Controller.java类是启动GUI的代码。当用户输入游戏服务器的IP和端口并命中提交时,侦听该Socket的服务器然后实例化Controller.java内部类ClientServiceThread的线程。这个类应该在GUI之间发送消息 - 客户端 - 服务器。
我的问题是在外部类(Controller.java)中我有一个名为" messageText"的实例变量。稍后当用户向Chatbox输入消息时,我将该文本分配给" messageText"变量。但是,当我尝试在ClientServiceThread中获取该变量时,它始终为null。我相信这是因为服务器同时创建了一个新客户端和一个新控制器,这意味着我试图获得的变量实际上没有被修改过。
服务器代码段
public void run() {
try {
myServerSocket = new ServerSocket(8888);
} catch(IOException ioe) {
System.out.println("Could not create server socket on port 8888. Quitting.");
System.exit(-1);
}
System.out.println("Server successfully started");
while(ServerOn) {
try {
Socket clientSocket = myServerSocket.accept();
Controller.ClientServiceThread cliThread = new Controller().new ClientServiceThread(clientSocket, clientidnum);
cliThread.start();
//adds clients to array in order they join
connectedClients[clientidnum] = cliThread;
//increments connected ID client var
clientidnum++;
} catch(IOException ioe) {
System.out.println("Exception found on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
Controller.java代码段
public class Controller extends Application implements Initializable {
Socket myClientSocket;
boolean m_bRunThread = true;
String hostname;
int hostportnumber;
private ObservableList<String> chatMessages = FXCollections.observableArrayList();
String messageText = "";
private void handleChatAction(ActionEvent event) throws IOException {
if (event.getSource() == sendchatButton){
String chat = chatInput.getText();
if(chat != null && !chat.trim().isEmpty()) {
chatMessages.add(chat);
messageText = chat;
chatmessagesList.setItems(chatMessages);
chatmessagesList.scrollTo(chatMessages.size());
}
chatInput.clear();
}
}
内部类ClientServiceThread代码段
class ClientServiceThread extends Thread {
Socket myClientSocket;
boolean m_bRunThread = true;
String hostname;
int hostportnumber;
int id;
public ClientServiceThread() {
super();
}
ClientServiceThread(Socket s, int clientid) {
myClientSocket = s;
id = clientid;
}
public String getTextField(){
if(Controller.this.messageText != "") {
return Controller.this.messageText;
}
else {
return "";
}
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
System.out.println("Accepted Client Address - " + myClientSocket.getInetAddress().getHostName());
try {
in = new BufferedReader(new InputStreamReader(myClientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(myClientSocket.getOutputStream()));
while(m_bRunThread) {
String clientCommand = getTextField();
System.out.println("Client Says :" + clientCommand);
我为巨大的代码墙道歉。我已经删除了数百行代码,以减少筛选所需的数量。这个错误确实阻碍了我,除非客户端可以与服务器通信,否则我无法开发实际的游戏。
如果您希望查看完整的代码文件,可以使用以下链接。谢谢!
https://gist.github.com/anonymous/0961189791b8127598b3b3d7ca527987