1

I have a technogical question regarding Java Sockets.

For example lets assume I have one Java Sockets Server and n multiple clients. Is it possible to send data from the Server to any or all Clients in nearly realtime?

More precisely:

  • Is there kind of Listener which can be implemented in a Sockets Client?
  • or do I need a loop in the client code where I ask every x milliseconds if there is a task for me?

Can somebody tell me what approach would be the best one? And in addition if somebody has a code example I would be happy too.

Thanks!

1
  • The listener exists. It's called selector and can be used with java nio channels, i.e. ServerSocketChannel and SocketChannel in your case. Further you wouldn't need to loop in the first place, since read on io socket's inputstream blocks. Commented Dec 18, 2014 at 10:55

1 Answer 1

4

You can establish a Thread in your client which listens to the socket and waits. It will continue when it gets data from the server.

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;
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

I'd use Runnable or Callable over Thread. And the use of ObjectInputStream implies that all the clients use java.
I know, feel free to optimize it your way. I only want to show an example
thanks for the input, unfortunately I am bound to Java 1.6 and try-with-resources is not available for 1.6. :-(
and whats the class Client? I thought both Server and Client are based on the type Socket
Sorry, Client is a selfmade interface i used to offer status access and management for the whole client. Things like isRunning() stop() start() and so on.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.