Solon v3.0.3

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());
        
        if(message.isRequest()){
            session.replyEnd(message, new StringEntity("And you too."));
        }
    }
}

2、客户端

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

        
        //发送并请求(且,等待答复)
        Entity response = session.sendAndRequest("/demo", new StringEntity("Helloworld server!")).await();
        System.out.println("客户端:我收到:" + response);
    }
}