首页 > 解决方案 > 如何使用套接字制作 JavaFX 聊天应用程序?

问题描述

我正在制作一个聊天应用程序,可用于通过 LAN 连接向其他计算机发送消息。我是 Java Networking 的新手,我在网上找到的 Socket 教程并没有帮到我很多忙。

我已经编写了应用程序本身的视觉效果,但我希望能够将客户端连接到同一台服务器并在每台设备上显示消息。

套接字和网络让我有点困惑,我尝试了一些关于套接字的在线教程和网页,但没有成功。

这是应用程序视觉效果的代码。

public class cli {

    static Stage window;
    static Pane layout = new Pane();
    static Scene scene;
    static String name;
    public static String message;
    static TextArea a = new TextArea();
    DataInputStream din;
    DataInputStream dout;

    public static void main(String[] args) {
    }
    public static void display() throws Exception {

        scene  = new Scene(layout, 500, 500);

        Stage window = new Stage();
        System.out.println("Enter a username!");
        window.setScene(scene);

        TextField t = new TextField();
        Button send = new Button("Send");
        TextArea log = new TextArea();
        log.setVisible(false);
        log.setEditable(false);

        a.setEditable(false);
        a.setTranslateX(50);
        a.setTranslateY(25);
        a.setMaxWidth(400);
        a.setMaxHeight(450);
        a.setMinHeight(450);
        t.setMaxHeight(20);
        t.setMaxWidth(350);
        send.setMaxWidth(50);
        t.setLayoutY(445);
        send.setLayoutY(445);
        t.setLayoutX(55);
        t.setMinWidth(340);
        send.setLayoutX(400);

        a.appendText("Group chat started at " + new Date() + "!" + "\n");
        a.appendText("Current Members: " + "\n");
        send.setOnAction(e -> {
            message = t.getText();
            System.out.println(message);
            if (message != null && message.length() >= 1) {
                a.appendText("[Client]" + " -> " + message + "\n");
                log.appendText("[Client] @ " + new Date() + " -> " + message + "\n");
            } else {

            }
        });


        layout.getChildren().addAll(a, t, send);
        window.show();
}
}

它应该看起来像这样: https ://imgur.com/a/k5GYhpL

本质上,我希望每个连接的客户端都有自己的应用程序窗口,并且每当用户键入内容时,它都会将该消息发送给每个客户端。

如果有人可以引导我完成这将非常有帮助。谢谢!:)

标签: javajavafx

解决方案


推荐阅读