当前位置: 首页>>代码示例>>Java>>正文


Java TextWebSocketFrame类代码示例

本文整理汇总了Java中io.netty.handler.codec.http.websocketx.TextWebSocketFrame的典型用法代码示例。如果您正苦于以下问题:Java TextWebSocketFrame类的具体用法?Java TextWebSocketFrame怎么用?Java TextWebSocketFrame使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


TextWebSocketFrame类属于io.netty.handler.codec.http.websocketx包,在下文中一共展示了TextWebSocketFrame类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handleWebSocketFrame

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format(
                "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame)));
    }

    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise());
    } else if (frame instanceof TextWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof PongWebSocketFrame) {
        frame.release();
        // Ignore
    } else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }
}
 
开发者ID:wuyinxian124,项目名称:netty4.0.27Learn,代码行数:25,代码来源:AutobahnServerHandler.java

示例2: channelRead0

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Override
public void channelRead0(ChannelHandlerContext context, Object message) throws Exception {
  Channel channel = context.channel();
  if (message instanceof FullHttpResponse) {
    checkState(!handshaker.isHandshakeComplete());
    try {
      handshaker.finishHandshake(channel, (FullHttpResponse) message);
      delegate.onOpen();
    } catch (WebSocketHandshakeException e) {
      delegate.onError(e);
    }
  } else if (message instanceof TextWebSocketFrame) {
    delegate.onMessage(((TextWebSocketFrame) message).text());
  } else {
    checkState(message instanceof CloseWebSocketFrame);
    delegate.onClose();
  }
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:19,代码来源:NettyWebSocketClient.java

示例3: broadMessage

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
/**
 * 广播
 * @param buildmessage: 经过build的Protocol
 */
public void broadMessage(String buildmessage){
    if (!BlankUtil.isBlank(buildmessage)){
        try {
            rwLock.readLock().lock();
            Set<Channel> keySet = chatUserMap.keySet();
            for (Channel ch : keySet) {
                ChatUser cUser = chatUserMap.get(ch);
                if (cUser == null || !cUser.isAuth()) continue;
                ch.writeAndFlush(new TextWebSocketFrame(buildmessage));
            }
        }finally {
            rwLock.readLock().unlock();
        }
    }
}
 
开发者ID:ChinaLHR,项目名称:JavaQuarkBBS,代码行数:20,代码来源:ChannelManager.java

示例4: broadcastMess

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
/**
 * 广播普通消息
 *
 * @param message
 */
public static void broadcastMess(int uid, String nick, String message) {
    if (!BlankUtil.isBlank(message)) {
        try {
            rwLock.readLock().lock();
            Set<Channel> keySet = userInfos.keySet();
            for (Channel ch : keySet) {
                UserInfo userInfo = userInfos.get(ch);
                if (userInfo == null || !userInfo.isAuth()) continue;
                ch.writeAndFlush(new TextWebSocketFrame(ChatProto.buildMessProto(uid, nick, message)));
            }
        } finally {
            rwLock.readLock().unlock();
        }
    }
}
 
开发者ID:beyondfengyu,项目名称:HappyChat,代码行数:21,代码来源:UserInfoManager.java

示例5: handlerWebSocketFrame

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
private void handlerWebSocketFrame(ChannelHandlerContext ctx,
		WebSocketFrame frame) {
	// 判断是否关闭链路的指令
	if (frame instanceof CloseWebSocketFrame) {
		socketServerHandshaker.close(ctx.channel(),
				(CloseWebSocketFrame) frame.retain());
	}
	// 判断是否ping消息
	if (frame instanceof PingWebSocketFrame) {
		ctx.channel().write(
				new PongWebSocketFrame(frame.content().retain()));
		return;
	}
	// 本例程仅支持文本消息,不支持二进制消息
	if (!(frame instanceof TextWebSocketFrame)) {
		throw new UnsupportedOperationException(String.format(
				"%s frame types not supported", frame.getClass().getName()));
	}
	// 返回应答消息
	String request = ((TextWebSocketFrame) frame).text();
	System.out.println("服务端收到:" + request);
	TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString()
			+ ctx.channel().id() + ":" + request);
	// 群发
	group.writeAndFlush(tws);
}
 
开发者ID:hdcuican,项目名称:java_learn,代码行数:27,代码来源:WebSocketServerHandler.java

示例6: userEventTriggered

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
	// 如果WebSocket握手完成
	if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
		// 删除ChannelPipeline中的HttpRequestHttpHandler
		ctx.pipeline().remove(HttpRequestHandler.class);
		String user = ChatUtils.addChannel(ctx.channel());
		Users us = new Users(user);
		ctx.channel().writeAndFlush(new TextWebSocketFrame(us.getCurrentUser()));
		// 写一个消息到ChannelGroup
		group.writeAndFlush(new TextWebSocketFrame(user + " 加入聊天室."));
		// 将channel添加到ChannelGroup
		group.add(ctx.channel());
		group.writeAndFlush(new TextWebSocketFrame(us.getAllUsers()));
	} else {
		super.userEventTriggered(ctx, evt);
	}
}
 
开发者ID:janzolau1987,项目名称:study-netty,代码行数:19,代码来源:TextWebSocketFrameHandler.java

示例7: testCreateSubscriptionWithMissingSessionId

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testCreateSubscriptionWithMissingSessionId() throws Exception {
    decoder = new WebSocketRequestDecoder(config);
    // @formatter:off
    String request = "{ "+ 
      "\"operation\" : \"create\", " +
      "\"subscriptionId\" : \"1234\"" + 
    " }";
    // @formatter:on
    TextWebSocketFrame frame = new TextWebSocketFrame();
    frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8));
    decoder.decode(ctx, frame, results);
    Assert.assertNotNull(ctx.msg);
    Assert.assertEquals(CloseWebSocketFrame.class, ctx.msg.getClass());
    Assert.assertEquals(1008, ((CloseWebSocketFrame) ctx.msg).statusCode());
    Assert.assertEquals("User must log in", ((CloseWebSocketFrame) ctx.msg).reasonText());
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:18,代码来源:WebSocketRequestDecoderTest.java

示例8: testCreateSubscriptionWithInvalidSessionIdAndNonAnonymousAccess

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testCreateSubscriptionWithInvalidSessionIdAndNonAnonymousAccess() throws Exception {
    ctx.channel().attr(SubscriptionRegistry.SESSION_ID_ATTR)
            .set(URLEncoder.encode(UUID.randomUUID().toString(), StandardCharsets.UTF_8.name()));
    decoder = new WebSocketRequestDecoder(config);
    // @formatter:off
    String request = "{ "+ 
      "\"operation\" : \"create\", " +
      "\"subscriptionId\" : \"1234\"" + 
    " }";
    // @formatter:on
    TextWebSocketFrame frame = new TextWebSocketFrame();
    frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8));
    decoder.decode(ctx, frame, results);
    Assert.assertNotNull(ctx.msg);
    Assert.assertEquals(CloseWebSocketFrame.class, ctx.msg.getClass());
    Assert.assertEquals(1008, ((CloseWebSocketFrame) ctx.msg).statusCode());
    Assert.assertEquals("User must log in", ((CloseWebSocketFrame) ctx.msg).reasonText());
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:20,代码来源:WebSocketRequestDecoderTest.java

示例9: testCreateSubscriptionWithValidSessionIdAndNonAnonymousAccess

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testCreateSubscriptionWithValidSessionIdAndNonAnonymousAccess() throws Exception {
    ctx.channel().attr(SubscriptionRegistry.SESSION_ID_ATTR).set(cookie);
    decoder = new WebSocketRequestDecoder(config);
    // @formatter:off
    String request = "{ " + 
      "\"operation\" : \"create\"," + 
      "\"subscriptionId\" : \"" + cookie + "\"" +
    "}";
    // @formatter:on
    TextWebSocketFrame frame = new TextWebSocketFrame();
    frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8));
    decoder.decode(ctx, frame, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(CreateSubscription.class, results.get(0).getClass());
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:17,代码来源:WebSocketRequestDecoderTest.java

示例10: testSuggest

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testSuggest() throws Exception {
    // @formatter:off
	String request = 
			"{\n" +
			"    \"operation\" : \"suggest\",\n" +
	        "    \"sessionId\" : \"1234\",\n" +
	        "    \"type\": \"metrics\",\n" +
	        "    \"q\": \"sys.cpu.user\",\n" +
	        "    \"max\": 30\n" +    			
			"}";
	// @formatter:on
    decoder = new WebSocketRequestDecoder(anonConfig);
    TextWebSocketFrame frame = new TextWebSocketFrame();
    frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8));
    decoder.decode(ctx, frame, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SuggestRequest.class, results.get(0).getClass());
    SuggestRequest suggest = (SuggestRequest) results.iterator().next();
    Assert.assertEquals("metrics", suggest.getType());
    Assert.assertEquals("sys.cpu.user", suggest.getQuery().get());
    Assert.assertEquals(30, suggest.getMax());
    suggest.validate();
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:25,代码来源:WebSocketRequestDecoderTest.java

示例11: testWSAggregators

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testWSAggregators() throws Exception {
    try {
        AggregatorsRequest request = new AggregatorsRequest();
        ch.writeAndFlush(new TextWebSocketFrame(JsonUtil.getObjectMapper().writeValueAsString(request)));
        // Latency in TestConfiguration is 2s, wait for it
        sleepUninterruptibly(TestConfiguration.WAIT_SECONDS, TimeUnit.SECONDS);

        // Confirm receipt of all data sent to this point
        List<String> response = handler.getResponses();
        while (response.size() == 0 && handler.isConnected()) {
            LOG.info("Waiting for web socket response");
            sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
            response = handler.getResponses();
        }
        Assert.assertEquals(1, response.size());
        JsonUtil.getObjectMapper().readValue(response.get(0), AggregatorsResponse.class);
    } finally {
        ch.close().sync();
        s.shutdown();
        group.shutdownGracefully();
    }
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:24,代码来源:WebSocketIT.java

示例12: testWSMetrics

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testWSMetrics() throws Exception {
    try {
        MetricsRequest request = new MetricsRequest();
        ch.writeAndFlush(new TextWebSocketFrame(JsonUtil.getObjectMapper().writeValueAsString(request)));

        // Confirm receipt of all data sent to this point
        List<String> response = handler.getResponses();
        while (response.size() == 0 && handler.isConnected()) {
            LOG.info("Waiting for web socket response");
            sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
            response = handler.getResponses();
        }
        Assert.assertEquals(1, response.size());
        Assert.assertEquals("{\"metrics\":[]}", response.get(0));
    } finally {
        ch.close().sync();
        s.shutdown();
        group.shutdownGracefully();
    }
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:22,代码来源:WebSocketIT.java

示例13: testVersion

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Test
public void testVersion() throws Exception {
    try {
        String request = "{ \"operation\" : \"version\" }";
        ch.writeAndFlush(new TextWebSocketFrame(request));
        // Confirm receipt of all data sent to this point
        List<String> response = handler.getResponses();
        while (response.size() == 0 && handler.isConnected()) {
            LOG.info("Waiting for web socket response");
            sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
            response = handler.getResponses();
        }
        assertEquals(1, response.size());
        assertEquals(VersionRequest.VERSION, response.get(0));
    } finally {
        ch.close().sync();
        s.shutdown();
        group.shutdownGracefully();
    }
}
 
开发者ID:NationalSecurityAgency,项目名称:timely,代码行数:21,代码来源:WebSocketIT.java

示例14: handleFrame

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
private void handleFrame(Channel channel, WebSocketFrame frame, WebSocketUpgradeHandler handler, NettyWebSocket webSocket) throws Exception {
    if (frame instanceof CloseWebSocketFrame) {
        Channels.setDiscard(channel);
        CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame;
        webSocket.onClose(closeFrame.statusCode(), closeFrame.reasonText());
    } else {
        ByteBuf buf = frame.content();
        if (buf != null && buf.readableBytes() > 0) {
            HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(buf, frame.isFinalFragment());
            handler.onBodyPartReceived(part);

            if (frame instanceof BinaryWebSocketFrame) {
                webSocket.onBinaryFragment(part);
            } else if (frame instanceof TextWebSocketFrame) {
                webSocket.onTextFragment(part);
            } else if (frame instanceof PingWebSocketFrame) {
                webSocket.onPing(part);
            } else if (frame instanceof PongWebSocketFrame) {
                webSocket.onPong(part);
            }
        }
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:24,代码来源:WebSocketHandler.java

示例15: decode

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; //导入依赖的package包/类
@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final TextWebSocketFrame frame, final List<Object> objects) throws Exception {
    try {
        // the default serializer must be a MessageTextSerializer instance to be compatible with this decoder
        final MessageTextSerializer serializer = (MessageTextSerializer) select("application/json", Serializers.DEFAULT_REQUEST_SERIALIZER);

        // it's important to re-initialize these channel attributes as they apply globally to the channel. in
        // other words, the next request to this channel might not come with the same configuration and mixed
        // state can carry through from one request to the next
        channelHandlerContext.channel().attr(StateKey.SESSION).set(null);
        channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
        channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(false);

        objects.add(serializer.deserializeRequest(frame.text()));
    } catch (SerializationException se) {
        objects.add(RequestMessage.INVALID);
    }
}
 
开发者ID:PKUSilvester,项目名称:LiteGraph,代码行数:19,代码来源:WsGremlinTextRequestDecoder.java


注:本文中的io.netty.handler.codec.http.websocketx.TextWebSocketFrame类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。