1
回答
t-io WebSocket 如何主动向所有客户端推送
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

参照官方 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);
	}

 

举报
mymbrooks
发帖于3个月前 1回/166阅
顶部