Java套接字io服务器未从客户端接收特定事件

时间:2018-07-25 08:47:27

标签: java sockets io socket.io

我在IDEA中有一个简单的Java项目,具有基于com.corundumstudio.socketio.SocketIOServer的简单socketio服务器和简单的客户端。当我尝试将客户端连接到服务器时,它成功连接,日志证明了这一点。但是,当我尝试通过socket.emit()向服务器发送事件时,什么都没有发生(通过日志),但是客户端可以成功地从服务器接收通过server.getBroadcastOperations()。sendEvent()发送的事件。如何将事件从客户端发送到服务器?确实需要帮助,谢谢!

客户端展示:

package ru.cnv.application.core;

import io.reactivex.Observable;
import io.socket.client.IO;
import io.socket.client.Socket;
import ru.cnv.application.view.SampleViewverViewMessage;

import java.util.concurrent.TimeUnit;

public class TestClient {

    private static Socket socket;

    public static void main(String[] arguments) {
        try {
            socket = IO.socket("http://localhost:9092");
        } catch (Exception e) {
            e.printStackTrace();
        }

        socket.on(Socket.EVENT_CONNECT, args -> {
            SampleViewverViewMessage message = new SampleViewverViewMessage();
            message.setMessage("lol");
            System.out.println("connected");
            Observable.interval(1000, TimeUnit.MILLISECONDS).subscribe(aLong -> {
                socket.emit("message", message);
                System.out.println("try to send");
            });
        }).on(Socket.EVENT_CONNECT_ERROR, args -> {
            System.out.println("not connected");
        }).on(Socket.EVENT_ERROR, args -> {
            System.out.println("err");
        }).on("m", args -> {
            System.out.println("m");
        });

        socket.connect();
    }
}

服务器展示:

package ru.cnv.framework.view;

import com.corundumstudio.socketio.*;
import ru.cnv.application.view.SampleViewverViewMessage;
import ru.cnv.library.utils.GsonUtils;
import ru.cnv.library.view.PresenterView;

public abstract class SocketView implements PresenterView {

    public SocketView() {
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(9092);

        SocketIOServer server = new SocketIOServer(config);
        server.addEventListener("message", SampleViewverViewMessage.class, (client, data, ackRequest) -> {
            SampleViewverViewMessage message = new SampleViewverViewMessage();
            System.out.println(GsonUtils.objectToJson(message));
        });
        server.addConnectListener(client -> {
            System.out.println(GsonUtils.objectToJson("connected"));
            SampleViewverViewMessage message = new SampleViewverViewMessage();
            server.getBroadcastOperations().sendEvent("m", message);
        });

        server.start();

        try {
            Thread.sleep(100 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        server.stop();
    }
}

0 个答案:

没有答案