Java套接字 - 将数据从服务器发送到客户端

时间:2014-12-18 10:50:17

标签: java sockets network-programming client server

我有一个关于Java套接字的技术问题。

例如假设我有一个Java套接字服务器和n个多个客户端。 是否有可能几乎实时地将数据从服务器发送到任何或所有客户端?

更确切地说:

  • 是否有可以在套接字客户端中实现的监听器?
  • 或者我是否需要在客户端代码中使用循环,如果有任务,我每隔x毫秒会询问一次?

有人可以告诉我哪种方法最好吗? 此外,如果有人有代码示例,我也会很高兴。

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以在客户端中建立一个侦听套接字并等待的线程。当它从服务器获取数据时它将继续。

import java.io.IOException;
import java.io.ObjectInputStream;

import java.net.Socket;

public class ResponseThread extends Thread {

    private final Socket socket;

    /**
     * Client is a selfmade interface which has no direct connection to socket communication.
     * i build it to provide start(), stop() and isRunning() methods.
     */
    private final Client client;
    /**
     * @param client encapsulated methods to check and manage the client status itself.
     * @param socket the socket which is connected to the server.
     */
    public ResponseThread(final Client client, final Socket socket) {
        this.client = client;
        this.socket = socket;
    }

    @Override
    public void run() {
        ObjectInputStream reader  = null;
        try(ObjectInputStream reader = new ObjectInputStream(socket.getInputStream())) {
            while (client.isRunning()) {
                try {
                    // The thread will wait here until the server sends data.
                    final String line = (String) reader.readObject();
                    if (null == line || line.isEmpty()) {
                        client.stop();
                    } else {
                        System.out.println(line);
                    }
                } catch (IOException | ClassNotFoundException e) {
                    client.stop();
                }
            }
        } catch (IOException ex) {
            System.out.println("ERROR Abort reading. Could not establish InputStream from Socket.");
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                System.out.println("FATAL Could not close Socket.InputStream.");
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }
}
相关问题