本文整理匯總了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()));
}
}
示例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();
}
}
示例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();
}
}
}
示例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();
}
}
}
示例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);
}
示例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);
}
}
示例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());
}
示例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());
}
示例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());
}
示例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();
}
示例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();
}
}
示例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();
}
}
示例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();
}
}
示例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);
}
}
}
}
示例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);
}
}