客户端如何等待服务器响应

时间:2020-09-15 16:08:43

标签: 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 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 :(得分: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();