本文介绍了Java中的SocketIO Client,如何实现与netty-socketio Server一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于大学的实践课程,我必须用Java编写一个带有客户端/服务器基础结构的小游戏。我需要使用Websockets进行通信,其他学生的解决方案必须与我的兼容,为服务器端选择了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();


现在请你解释一下,客户代码怎么样?看起来和我应该使用哪个SocketIOClient(Netty只带来接口)的实现?如果你能告诉我产生输出的代码会很棒

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

推荐答案

您可以使用

以下是示例代码。

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

每个事件都可以为事件分配类别。
ie。

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

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

和listner类是

class MyEventListner implements Listener{
    @Override
    public void call(Object... args) {
        System.out.println("myEvent, msg="+args[0].toString());
    }
}

这篇关于Java中的SocketIO Client,如何实现与netty-socketio Server一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 18:38