6

for a practical course at university, I have to write a little game in Java, with a client/server infrastructure. I need to use Websockets for communication, and other students, whose solutions must be compatible with mine, chose the Netty SocketIO Server for the server-side (https://github.com/mrniko/netty-socketio/tree/master/src). I already know how to set up the server:



    Configuration config = new Configuration();
    config.setPort(1234);
    config.setHostname("localhost");

    server = new SocketIOServer(config);

    server.addConnectListener(
        (client) -> {
            System.out.println("Client has Connected!");
    });

    server.addEventListener("MESSAGE", String.class, 
        (client, message, ackRequest) -> {
            System.out.println("Client said: " + message);
    });

    server.start();


Now could you explain to me please, how should the client code look like and which implementation of SocketIOClient (Netty brings only the interface) should I use for it? Would be great if you could show me the code that would produce the output

Client has connected!
Client said: any message you'd like :)

I'm really stuck here and was already playing around with implementations like this one https://github.com/socketio/socket.io-client-java but still can't figure out how to build a client and connect to my server. Thanks for your help.

Felix

1
  • 1
    did you find the way to do a client with socketIO and java? I am in the same situation. Thanks! Commented Jan 12, 2017 at 0:15

1 Answer 1

3

You can use this

Here is sample code.

public class MySocketClient {
    public static  void main(String args[]) {
        Options options = new Options();
        options.reconnection= true;
        Socket socket = IO.socket("URL of socket.io server");

        //socket.on

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
              @Override
              public void call(Object... args) {
                  System.out.println("Connected");
              }

            })
            .on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                      System.out.println("Disonnected");
                  }

            });
        socket.connect();
    }
}

You can have seprate class for event each event. ie.

socket.on("myEvent", new MyEventListner())

and listner class is

class MyEventListner implements Listener{
    @Override
    public void call(Object... args) {
        System.out.println("myEvent, msg="+args[0].toString());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.