首页 > 解决方案 > 客户端如何等待服务器响应

问题描述

我有一个简单的服务器到客户端程序,可以让服务器向客户端发送文本,没有连接问题。但是,我不确定将更新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());
        }
        
    }

} 

标签: javaserverclient

解决方案


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();

推荐阅读