英文:
How does the client wait for a server response
问题
我有一个简单的服务器到客户端程序,允许服务器将文本发送到客户端,没有连接问题。然而,我不确定要将更新```JLabel```的while循环放在什么地方。如果我放```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(/* 在这里填入代码 */) {
l.setText(in.nextLine());
}
}
}
英文:
I have a simple server to client program that lets the server send text to the clients, There is no connection problems. However, I'm not sure what to put the while loop which updates the JLabel
of the sent text. If I put while(true)
I get an error saying 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());
}
}
}
答案1
得分: 0
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();
英文:
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");
}
}
}
Create a private nested class inside Client class.
Initiate the thread from Client class's main() method.
PollingThread mPollingThread = new PollingThread();
mPollingThread.start();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论