Java 客户端如何等待服务器响应
我有一个简单的服务器到客户端程序,让服务器发送文本到客户端,没有连接问题。但是,我不确定应该将while循环放在哪里,该循环会更新发送文本的Java 客户端如何等待服务器响应,java,server,client,Java,Server,Client,我有一个简单的服务器到客户端程序,让服务器发送文本到客户端,没有连接问题。但是,我不确定应该将while循环放在哪里,该循环会更新发送文本的JLabel。如果我把放在while(true)中,我会得到一个错误,说找不到行 import java.io.IOException; import java.net.Socket; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JLabel; import
JLabel
。如果我把放在while(true)
中,我会得到一个错误,说找不到行
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());
}
}
}
在客户端类内创建一个私有嵌套类
从客户端类的main()方法启动线程
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");
}
}
}
PollingThread mPollingThread = new PollingThread();
mPollingThread.start();