我在编写JavaFX聊天客户端的套接字端时遇到问题 . 这是我第一次以任何方式处理套接字,所以预计会有一些麻烦 . 我一直在关注此页面来设计服务器端 - 客户端:http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html

我的问题是将我输入GUI的文本导入DataInputSteam和DataOutputStream,以便同一服务器上的其他人可以看到更改 . 我不明白如何将UI中的文本转换为套接字可以使用的内容 .

这是我的控制器类的一部分:

@FXML
private TextArea messageArea;

@FXML
private Button sendButton;

private ChatClient client;

@FXML
public void initialize() {

    client = new ChatClient(ChatServer.HOSTNAME, ChatServer.PORT);

    sendButton.setOnAction(event -> {
        client.handle(messageArea.getText());
    });
}

ChatClient类是一个Runnable,它有一个连接到Socket的DataInputStream和DataOutputStream字段 . 我没有从链接中改变太多:

public class ChatClient implements Runnable {

private Socket socket;
private Thread thread;
private DataInputStream streamIn;
private DataOutputStream streamOut;
private ChatClientThread client;

public ChatClient(String serverName, int port) {
    System.out.println("Establishing connection...");
    try {
        socket = new Socket(serverName, port);
        System.out.println("Connected: " + socket);
        start();
    } catch (UnknownHostException e) {
       System.out.println("Unknown host: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("Unexpected: " + e.getMessage());
    }
}

@Override
public void run() {
    while (thread != null) {
        try {
            streamOut.writeUTF(streamIn.readUTF());
            streamOut.flush();
        } catch (IOException e) {
            System.out.println("Sending error: " + e.getMessage());
            stop();
        }
    }
}

public void handle(String msg) {
    try {
        streamOut.writeUTF(msg);
        streamOut.flush();
    } catch (IOException e) {
        System.out.println("Could not handle message: " + e.getMessage());
    }
    System.out.println(msg);
}

public void start() throws IOException {
    streamIn = new DataInputStream(socket.getInputStream());
    streamOut = new DataOutputStream(socket.getOutputStream());
    if (thread == null) {
        client = new ChatClientThread(this, socket);
        thread = new Thread(this);
        thread.start();
    }
}

所以在控制器类中,我调用处理流的handle方法 . 原始代码只是写入控制台,所以我不得不更改行:streamIn = new DataInputStream(System.in)to streamIn = new DataInputStream(socket.getInputStream());

还有一个ChatClientThread类,它扩展了Thread并在其run方法中调用了ChatClient.handle() .

我想我的问题是当writeUTF和readUTF与DataStream交互时如何更新GUI . 我知道streamOut.writeUTF(msg)将DataOutputStream更改为“拥有”该字符串,但我不确定我应该如何使用该数据流更新我的gui,以便使用该应用程序的所有客户端都可以看到更新 . 我现在拥有它的方式,如果我运行两个JavaFX应用程序实例,他们就不会通过UI或控制台进行通信 . 每当我点击发送按钮时,我的程序就会停止