Solon

Socket.D 小场景.消息上报模式 (v2)

</> markdown

本案以简单的消息上报模式为例演示:(就是我给你发,你不用理我)

1、服务端

//启动服务端
public class ServerApp {
    public static void main(String[] args) {
        //启动Solon容器(SocketD bean&plugin 由solon容器管理)
        Solon.start(ServerApp.class, args, app -> app.enableSocketD(true));
    }
}

//定义服务端监听
@ServerEndpoint("/")
public class ServerListener implements Listener {
    @Override
    public void onOpen(Session session) {
        System.out.println("有客户端链上来喽...");
    }

    @Override
    public void onMessage(Session session, Message message) {
        System.out.println("服务端:我收到:" + message.dataAsString());
    }
}

2、客户端

//启动客户端
public class ClientApp {
    public static void main(String[] args) throws Throwable {
        //创建会话(如果后端是WebSocekt,协议头为:sd:ws)
        ClientSession session = SocketD.createClient("sd:tcp://localhost:28080").open();
        
        //发送
        session.send("/demo", new StringEntity("Helloworld server!"));
    }
}