Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SocketIO Client in Java, how to implement working with netty-socketio Server?

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

like image 615
feliXilef Avatar asked Oct 30 '22 07:10

feliXilef


1 Answers

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());
    }
}
like image 105
Nitin Avatar answered Nov 09 '22 23:11

Nitin