java - 客户端如何等待服务器响应
问题描述
我有一个简单的服务器到客户端程序,可以让服务器向客户端发送文本,没有连接问题。但是,我不确定将更新JLabel
已发送文本的 while 循环放在什么位置。如果我输入,while(true)
我会收到一条错误消息,说no lines found。
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Client {
private static JLabel l = new JLabel();
public Client() {
JFrame f = new JFrame("Client");
JPanel p = new JPanel(null);
f.setSize(300, 150);
f.setLocationRelativeTo(null);
l.setSize(300, 20);
l.setLocation(0, 65);
p.add(l);
f.add(p);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws IOException {
new Client();
Socket socket = new Socket("localhost", 12000);
Scanner in = new Scanner(socket.getInputStream());
while(/* code goes here */) {
l.setText(in.nextLine());
}
}
}
解决方案
private class PollingThread implements Runnable {
public void run() {
while (true) {
try {
l.setText(in.nextLine());
} catch (/* */) {
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.d(TAG, "Thread interrupted");
}
}
}
在 Client 类中创建一个私有嵌套类。
从 Client 类的 main() 方法启动线程。
PollingThread mPollingThread = new PollingThread();
mPollingThread.start();
推荐阅读
- julia - 如何在 Julia 的函数中返回不同的东西
- python - Python添加时间限制并检查他们是否已经行动
- docker - 如何在主机上以确切用户身份运行 docker 容器?
- python - 我们可以用 python 更改对话流实现设置吗?
- android - Jitpack 不构建项目
- asp.net - Footable 分页限制在某些情况下不起作用
- c++ - 在 Visual Studio 2017 中使用库设置 vc++ 项目的正确方法
- c++ - C++ - 为什么是 std::function
无效的? - python - Python - ConnectionRefusedError、urllib3.exceptions.NewConnectionError 和 Colorama
- python - dlib-build@0.1.1 安装失败