t-io WebSocket 如何主动向所有客户端推送

mymbrooks 发布于 2017/09/01 15:23
阅读 1K+
收藏 0

参照官方 WebSocket 的例子:

public class WebSocketHandler implements IWsMsgHandler {
    @Override
    public HttpResponse handshake(HttpRequest request, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        return httpResponse;
    }

    @Override
    public Object onBytes(WsRequestPacket websocketPacket, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    @Override
    public Object onClose(WsRequestPacket websocketPacket, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    @Override
    public Object onText(WsRequestPacket websocketPacket, String text, ChannelContext channelContext) throws Exception {
        return text;
    }
}
                WebSocketHandler webSocketHandler = new WebSocketHandler();
                WsServerStarter wsServerStarter = new WsServerStarter();
                wsServerStarter.start(9321, webSocketHandler);
        ws = new WebSocket("ws://localhost:9321");
        ws.onmessage = function (event) {
            alert(event.data);
        };
        ws.onclose = function (event) {
            alert(event.data);
        };
        ws.onopen = function (event) {
            ws.send("hello tio server");
        };
        ws.onerror = function (event) {
            alert(event.data);
        };

运行可以收到消息,现在我想在服务端主动推送消息给所有的客户端,查了下 API,有个

sendToAll 方法,但是参数 GroupContext 如何设置呢,我想给所有的客户端主动推送消息。

	/**
	 * 发消息到所有连接
	 * @param groupContext
	 * @param packet
	 * @param channelContextFilter
	 * @author tanyaowu
	 */
	public static void sendToAll(GroupContext groupContext, Packet packet, ChannelContextFilter channelContextFilter) {
		sendToAll(groupContext, packet, channelContextFilter, false);
	}

 

加载中
0
talent-tan
talent-tan

先拿到WsServerStarter,然后org.tio.websocket.server.WsServerStarter.getServerGroupContext(),WsServerStarter是你启动服务器时创建的,你用一个全局变量存储就可以了

0
东湖畔新家
东湖畔新家
GroupContext

怎么构造

 

0
编号uip
编号uip

引用来自“talent-tan”的评论

先拿到WsServerStarter,然后org.tio.websocket.server.WsServerStarter.getServerGroupContext(),WsServerStarter是你启动服务器时创建的,你用一个全局变量存储就可以了

ddddddwerwerw

编号uip
编号uip
fffffffewrqt
返回顶部
顶部