java - 如何使用套接字制作 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
本质上,我希望每个连接的客户端都有自己的应用程序窗口,并且每当用户键入内容时,它都会将该消息发送给每个客户端。
如果有人可以引导我完成这将非常有帮助。谢谢!:)
解决方案
推荐阅读
- python - 是否可以编写一个带有隐藏方法的 Python 类,该方法只有在设置了特定属性时才能调用?
- python - 在类别数组上细分ndarray
- java - Java Socket 不允许摆动框架出现
- java - 抛出异常以强制退出递归有效吗?
- visual-studio-code - 在 VS Code 中创建新文件的替代方法?
- postgresql - 首先尝试更新的 INSERT ... ON CONFLICT 相当于什么?
- prism - Fluent.Ribbon 的 RegionAdapter
- python - 如何修复部署在 AWS EC2 中但 CSS 和照片不起作用的 Django 项目
- python - PyTorch 数据集:ImageFolder 和子文件夹过滤
- javascript - 为什么值为空?