英文:
How to handle 2 process at once but still responsive gui java
问题
I understand your request. Here's the translated code:
这是服务器部分:
public void server(int port) {
try {
try (ServerSocket server = new ServerSocket(port)) {
serverStatus = "Server已经开始在端口" + port + "上运行";
while (true) {
// 等待客户端连接
serverStatus = "等待客户端连接...";
Socket robot = server.accept();
serverStatus = "已连接";
// 将客户端连接添加到连接列表
robotSockets.add(robot);
// 创建线程来处理每个客户端连接
Thread robotThread = new Thread(new ClientHandler(robot));
robotThread.start();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
这是客户端部分:
public void client(Consumer<String> onMessageReceived) {
Thread clientSideThread = new Thread(() -> {
try {
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String message = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
onMessageReceived.accept(message);
}
} catch (IOException e) {
e.printStackTrace();
if (!socket.isClosed()) {
this.statusKoneksi = "连接已断开";
}
}
});
clientSideThread.start();
}
如何使程序既可以作为服务器等待客户端连接,同时也可以作为客户端连接到服务器,而且仍然能够响应性地工作呢?
英文:
So i making a program that have gui and can be client/server at same time but my program only process one progress for example as a server wait for client to connect and wait for it but after that my program is freeze
This is server
public void server(int port) {
try {
try (ServerSocket server = new ServerSocket(port)) {
serverStatus = ("Server telah dimulai di port " + port);
while (true) {
// Menunggu koneksi dari client
serverStatus = ("Menunggu koneksi dari client...");
Socket robot = server.accept();
serverStatus = ("Terhubung");
// Menambahkan koneksi client ke daftar koneksi
robotSockets.add(robot);
// Membuat thread untuk menangani setiap koneksi client
Thread robotThread = new Thread(new ClientHandler(robot));
robotThread.start();
}
}
Here for client
public void client(Consumer<String> onMessageReceived) {
Thread clientSideThread = new Thread(() -> {
try {
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String message = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
onMessageReceived.accept(message);
}
} catch (IOException e) {
e.printStackTrace();
if (!socket.isClosed()) {
this.statusKoneksi = "Terputus";
}
}
});
clientSideThread.start();
}
So how to make this program can handle be server and client but still working responsive?, as server wait client to connect and at same time as client can connect to server?
答案1
得分: 0
可以使用不同的线程。
一个线程用于监听套接字连接,另一个线程执行其他GUI任务。
英文:
You can use different threads.
One thread is listen for the socket connection, another is doing other GUI tasks.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论