这篇文章主要围绕javax.websocket.Decoder.TextStream的实例源码和javasocket源码展开,旨在为您提供一份详细的参考资料。我们将全面介绍javax.websocke
这篇文章主要围绕javax.websocket.Decoder.TextStream的实例源码和java socket源码展开,旨在为您提供一份详细的参考资料。我们将全面介绍javax.websocket.Decoder.TextStream的实例源码的优缺点,解答java socket源码的相关问题,同时也会为您带来com.facebook.react.bridge.WebsocketJavaScriptExecutor的实例源码、com.facebook.react.modules.websocket.WebSocketModule的实例源码、io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码的实用方法。
本文目录一览:- javax.websocket.Decoder.TextStream的实例源码(java socket源码)
- com.facebook.react.bridge.WebsocketJavaScriptExecutor的实例源码
- com.facebook.react.modules.websocket.WebSocketModule的实例源码
- io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码
- io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码
javax.websocket.Decoder.TextStream的实例源码(java socket源码)
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,message); } // Handle full decoders for (Decoder decoder : decoders) { if (decoder instanceof Text) { if (((Text<?>) decoder).willDecode(message)) { return ((Text<?>) decoder).decode(message); } } else { StringReader r = new StringReader(message); try { return ((TextStream<?>) decoder).decode(r); } catch (IOException ioe) { throw new DecodeException(message,sm.getString( "pojoMessageHandlerWhole.decodeIoFail"),ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,sm.getString("pojoMessageHandlerWhole.decodeIoFail"),ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
public DecoderMatch(Class<?> target,List<DecoderEntry> decoderEntries) { this.target = target; for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom(target)) { if (Binary.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (BinaryStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else if (Text.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (TextStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else { throw new IllegalArgumentException( sm.getString("util.unkNownDecoderType")); } } } }
public DecoderMatch(Class<?> target,List<DecoderEntry> decoderEntries) { this.target = target; for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom(target)) { if (Binary.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (BinaryStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else if (Text.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (TextStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else { throw new IllegalArgumentException( sm.getString("util.unkNownDecoderType")); } } } }
public DecoderMatch(Class<?> target,List<DecoderEntry> decoderEntries) { this.target = target; for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom(target)) { if (Binary.class.isAssignableFrom(decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (BinaryStream.class.isAssignableFrom(decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else if (Text.class.isAssignableFrom(decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (TextStream.class.isAssignableFrom(decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else { throw new IllegalArgumentException(sm.getString("util.unkNownDecoderType")); } } } }
public DecoderMatch(Class<?> target,List<DecoderEntry> decoderEntries) { for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom(target)) { if (Binary.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (BinaryStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else if (Text.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (TextStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else { throw new IllegalArgumentException( sm.getString("util.unkNownDecoderType")); } } } }
public DecoderMatch(Class<?> target,List<DecoderEntry> decoderEntries) { for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom(target)) { if (Binary.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (BinaryStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else if (Text.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (TextStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else { throw new IllegalArgumentException( sm.getString("util.unkNownDecoderType")); } } } }
com.facebook.react.bridge.WebsocketJavaScriptExecutor的实例源码
private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( final ProgressDialog progressDialog,final SimpleSettableFuture<Boolean> future) { return new WebsocketJavaScriptExecutor.JSExecutorConnectCallback() { @Override public void onSuccess() { future.set(true); progressDialog.dismiss(); } @Override public void onFailure(final Throwable cause) { progressDialog.dismiss(); FLog.e(ReactConstants.TAG,"Unable to connect to remote debugger",cause); future.setException( new IOException( mApplicationContext.getString(R.string.catalyst_remotedbg_error),cause)); } }; }
private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( final ProgressDialog progressDialog,cause)); } }; }
private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( final ProgressDialog progressDialog,cause)); } }; }
com.facebook.react.modules.websocket.WebSocketModule的实例源码
@Override public List<NativeModule> createNativeModules(ReactApplicationContext catalystApplicationContext) { return Arrays.<NativeModule>asList( // Core list new AndroidInfoModule(),new ExceptionsManagerModule(reactInstanceManager.getDevSupportManager()),new AppStateModule(catalystApplicationContext),new Timing(catalystApplicationContext,reactInstanceManager.getDevSupportManager()),new UIManagerStubModule(catalystApplicationContext),new Sourcecodemodule(catalystApplicationContext),new JSCHeapCapture(catalystApplicationContext),// Main list new AsyncStorageModule(catalystApplicationContext),new IntentModule(catalystApplicationContext),new LocationModule(catalystApplicationContext),new NetworkingModule(catalystApplicationContext),new NetInfoModule(catalystApplicationContext),new VibrationModule(catalystApplicationContext),new WebSocketModule(catalystApplicationContext),new ThreadSelfModule(catalystApplicationContext) ); }
@Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList( new AppStateModule(reactContext),new AsyncStorageModule(reactContext),new CameraRollManager(reactContext),new ClipboardModule(reactContext),new DatePickerDialogModule(reactContext),new DialogModule(reactContext),new FrescoModule(reactContext),new ImageEditingManager(reactContext),new ImageStoreManager(reactContext),new IntentModule(reactContext),new LocationModule(reactContext),new NetworkingModule(reactContext),new NetInfoModule(reactContext),new StatusBarModule(reactContext),new TimePickerDialogModule(reactContext),new ToastModule(reactContext),new VibrationModule(reactContext),new WebSocketModule(reactContext) ); }
@Override public List<NativeModule> createNativeModules(ReactApplicationContext catalystApplicationContext) { return Arrays.<NativeModule>asList( // Core list new AndroidInfoModule(),new Sourcecodemodule(reactInstanceManager.getSourceUrl()),new WorkerSelfModule(catalystApplicationContext) ); }
@Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList( new AppStateModule(reactContext),new WebSocketModule(reactContext) ); }
@Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList( new AppStateModule(reactContext),new ImageLoaderModule(reactContext),new WebSocketModule(reactContext) ); }
@Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList( new AsyncStorageModule(reactContext),// new ClipboardModule(reactContext),// new NetInfoModule(reactContext),new WebSocketModule(reactContext)); // new ToastModule(reactContext)); }
io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码
@Override public void channelRead0(ChannelHandlerContext ctx,Object msg) { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); System.out.println("WebSocket Client UID:[" + this.uid + "] handshaker connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof BinaryWebSocketFrame) { try { Object obj = protobufDecoder.decode(((BinaryWebSocketFrame) msg).content()); resQueue.add((Response.HeshResMessage)obj); } catch (Exception e) { e.printstacktrace(); } } }
@Override protected void encode(ChannelHandlerContext ctx,Proto proto,List<Object> list) throws Exception { ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); if (proto.getBody() != null) { byteBuf.writeInt(Proto.HEADER_LENGTH + proto.getBody().length); byteBuf.writeShort(Proto.HEADER_LENGTH); byteBuf.writeShort(Proto.VERSION); byteBuf.writeInt(proto.getoperation()); byteBuf.writeInt(proto.getSeqId()); byteBuf.writeBytes(proto.getBody()); } else { byteBuf.writeInt(Proto.HEADER_LENGTH); byteBuf.writeShort(Proto.HEADER_LENGTH); byteBuf.writeShort(Proto.VERSION); byteBuf.writeInt(proto.getoperation()); byteBuf.writeInt(proto.getSeqId()); } list.add(new BinaryWebSocketFrame(byteBuf)); logger.debug("encode: {}",proto); }
@Test public void testVersion() throws Exception { try { String uuid = UUID.randomUUID().toString(); VersionRequest request = new VersionRequest(); request.setRequestId(uuid); ch.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(JsonSerializer.getobjectMapper() .writeValueAsBytes(request)))); // Confirm receipt of all data sent to this point List<byte[]> 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()); VersionResponse version = JsonSerializer.getobjectMapper() .readValue(response.get(0),VersionResponse.class); assertEquals(VersionResponse.VERSION,version.getVersion()); assertEquals(uuid,version.getRequestId()); } finally { ch.close().sync(); s.shutdown(); group.shutdownGracefully(); } }
@SuppressWarnings({ "unchecked","rawtypes" }) @Override protected void encode(ChannelHandlerContext ctx,Packet packet,List out) throws Exception { ByteBuf buf = ctx.alloc().buffer().order(ByteOrder.LITTLE_ENDIAN); int packetId = PacketRegistry.SERVER2CLIENT.getPacketId(packet.getClass()); if (packetId == -1) { throw new IllegalArgumentException("Provided packet is not registered as a clientbound packet!"); } buf.writeByte(packetId); packet.writeData(buf); new BinaryWebSocketFrame(buf); out.add(new BinaryWebSocketFrame(buf)); Log.logDebug("Sent packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") to " + ctx.channel().remoteAddress()); }
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); } } } }
private Message decodeWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return null; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return null; } if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; return parseMessage(textFrame.content()); } if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; return parseMessage(binFrame.content()); } log.warn("Message format error: " + frame); return null; }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } }
@Override public void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { System.out.println("client channelRead0 "+ctx); Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } if(msg instanceof WebSocketFrame){ WebSocketFrame frame = (WebSocketFrame)msg; if(frame instanceof BinaryWebSocketFrame){ handleWebSocketFrame(ctx,frame); } return; } return; }
@Override public void channelRead0(ChannelHandlerContext ctx,frame); } return; } sendRealTimeMessageTest(ctx); return; }
@Override protected void channelRead0(ChannelHandlerContext context,Object message) throws Exception { final Channel channel = context.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(channel,(FullHttpResponse) message); channel.pipeline().addBefore(HANDLER_NAME,"websocket-frame-aggregator",new WebSocketFrameAggregator(64 * 1024)); subscriber.onStart(); return; } if (message instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) message; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ",content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) message; if (frame instanceof PingWebSocketFrame) { context.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame)frame).retain().content())); } else if (frame instanceof BinaryWebSocketFrame) { final ByteBufInputStream input = new ByteBufInputStream(((BinaryWebSocketFrame)message).content()); final Envelope envelope = Envelope.ADAPTER.decode(input); subscriber.onNext(envelope); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } }
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())); } }
private ReactiveSocketWebSocketClient(WebSocketConnection wsConn) { this.reactiveSocket = ReactiveSocket.createRequestor(); connect = this.reactiveSocket.connect( new DuplexConnection() { @Override public Publisher<Frame> getinput() { return toPublisher(wsConn.getinput().map(frame -> { return Frame.from(frame.content().nioBuffer()); })); } @Override public Publisher<Void> addOutput(Publisher<Frame> o) { // had to use writeAndFlushOnEach instead of write for frames to get through // Todo determine if that's expected or not Publisher<Void> p = toPublisher(wsConn.writeAndFlushOnEach(toObservable(o) .map(frame -> new BinaryWebSocketFrame(Unpooled.wrappedBuffer(frame.getByteBuffer()))) )); return p; } }); }
/** * Use this method as the RxNetty HttpServer WebSocket handler. * * @param ws * @return */ public Observable<Void> acceptWebsocket(WebSocketConnection ws) { return toObservable(reactiveSocket.connect(new DuplexConnection() { @Override public Publisher<Frame> getinput() { return toPublisher(ws.getinput().map(frame -> { // Todo is this copying bytes? try { return Frame.from(frame.content().nioBuffer()); } catch (Exception e) { e.printstacktrace(); throw new RuntimeException(e); } })); } @Override public Publisher<Void> addOutput(Publisher<Frame> o) { // had to use writeAndFlushOnEach instead of write for frames to reliably get through // Todo determine if that's expected or not return toPublisher(ws.writeAndFlushOnEach(toObservable(o).map(frame -> { return new BinaryWebSocketFrame(Unpooled.wrappedBuffer(frame.getByteBuffer())); }))); } })); }
@Override public void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); handshakeFuture.setSuccess(); return; } if (!(msg instanceof BinaryWebSocketFrame)) { ch.close(); log.warn("Received {},closing",msg); return; } byte[] b = extractBytes(msg); ctx.fireChannelRead(b); }
@Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws UnkNownWebSocketFrameTypeException,ServerConnectorException { if (!(msg instanceof WebSocketFrame)) { logger.error("Expecting WebSocketFrame. UnkNown type."); throw new UnkNownWebSocketFrameTypeException("Expecting WebSocketFrame. UnkNown type."); } if (msg instanceof TextWebSocketFrame) { notifyTextMessage((TextWebSocketFrame) msg); } else if (msg instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) msg); } else if (msg instanceof CloseWebSocketFrame) { notifyCloseMessage((CloseWebSocketFrame) msg); } else if (msg instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) msg); } else if (msg instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) msg); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,WebSocketFrame frame) throws Exception { if (frame instanceof TextWebSocketFrame) { // Echos the same text String text = ((TextWebSocketFrame) frame).text(); if (PING.equals(text)) { ctx.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{1,2,3,4}))); return; } ctx.channel().writeAndFlush(new TextWebSocketFrame(text)); } else if (frame instanceof BinaryWebSocketFrame) { ctx.channel().writeAndFlush(frame.retain()); } else if (frame instanceof CloseWebSocketFrame) { ctx.close(); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,frame.getClass() .getName())); } }
private void performSend(byte[] raw) throws IOException { if (this.outBuf != null) { this.outBuf.write(raw); raw = this.outBuf.toByteArray(); this.outBuf = null; } //char[] encoded = Base64.encode(raw); if (this.binary) { this.ctx.channel().write(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(raw))); } else { this.ctx.channel().write(new TextWebSocketFrame(StringUtil.toUtfString(raw))); } }
@Override public void write(ChannelHandlerContext ctx,Object msg,ChannelPromise promise) throws Exception { LOG.trace("NettyServerHandler: Channel write: {}",msg); if (isWebSocketServer() && msg instanceof ByteBuf) { if(isFragmentWrites()) { ByteBuf orig = (ByteBuf) msg; int origIndex = orig.readerIndex(); int split = orig.readableBytes()/2; ByteBuf part1 = orig.copy(origIndex,split); LOG.trace("NettyServerHandler: Part1: {}",part1); orig.readerIndex(origIndex + split); LOG.trace("NettyServerHandler: Part2: {}",orig); BinaryWebSocketFrame frame1 = new BinaryWebSocketFrame(false,part1); ctx.writeAndFlush(frame1); ContinuationWebSocketFrame frame2 = new ContinuationWebSocketFrame(true,orig); ctx.write(frame2,promise); } else { BinaryWebSocketFrame frame = new BinaryWebSocketFrame((ByteBuf) msg); ctx.write(frame,promise); } } else { ctx.write(msg,promise); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,frame.content())); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass() .getName())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); } }
public void handle(final Object msg) { ready(); if (msg instanceof TextWebSocketFrame) { onTextCallback.accept(((TextWebSocketFrame) msg).text()); } else if (msg instanceof BinaryWebSocketFrame) { onBinaryCallback.accept(((BinaryWebSocketFrame) msg).content().nioBuffer()); } else if (msg instanceof CloseWebSocketFrame) { CloseWebSocketFrame closeFrame = ((CloseWebSocketFrame) msg).retain(); int statusCode = closeFrame.statusCode(); onCloseCallback.accept(statusCode == -1 ? WebSocket.norMAL.code() : statusCode,Optional.ofNullable(closeFrame.reasonText())); handshaker.close(ctx.channel(),closeFrame).addListener(CLOSE); } else if (msg instanceof Throwable) { onErrorCallback.accept((Throwable) msg); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof BinaryWebSocketFrame) try { this.connection.onMessage(((BinaryWebSocketFrame) frame).content().retain()); } catch (Exception e) { logger.error("onMessage error",e); handshaker.close(ctx.channel(),new CloseWebSocketFrame(true,frame.content().clear() .writeShort(1000) .writeBytes(e.getMessage().getBytes(CharsetUtil.UTF_8)) .retain())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame msg) throws Exception { if (log.isDebugEnabled()) log.debug("Received {} WebSocketFrame: {} from channel: {}",getTransportType().getName(),msg,ctx.channel()); if (msg instanceof CloseWebSocketFrame) { sessionIdByChannel.remove(ctx.channel()); ChannelFuture f = ctx.writeAndFlush(msg); f.addListener(ChannelFutureListener.CLOSE); } else if (msg instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(msg.content())); } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame){ Packet packet = PacketDecoder.decodePacket(msg.content()); packet.setTransportType(getTransportType()); String sessionId = sessionIdByChannel.get(ctx.channel()); packet.setSessionId(sessionId); msg.release(); ctx.fireChannelRead(packet); } else { msg.release(); log.warn("{} frame type is not supported",msg.getClass().getName()); } }
@Override protected void decode(final ChannelHandlerContext ctx,final WebSocketFrame msg,final List<Object> out) throws Exception { if (msg instanceof BinaryWebSocketFrame) { ByteBuf content = msg.content(); // the content is passed to other handlers so they need to be retained. content.retain(); fragments.add(content); if (msg.isFinalFragment()) { if (fragments.size() == 1) { out.add(fragments.get(0)); } else { ByteBuf[] array = fragments.toArray(BYTE_BUF_TYPE); out.add(Unpooled.wrappedBuffer(array)); } fragments.clear(); } } else if (msg instanceof TextWebSocketFrame) { LOG.warn("Recieved a Websocket text frame. This was not expected. Ignoring it."); } }
/** * 向当前客户端发送数据 * @param message */ public void send(Message message) { byte[] bytes = message.toByteArray(); ByteBuf b = Unpooled.buffer(bytes.length); b.writeBytes(bytes); WebSocketFrame frame = new BinaryWebSocketFrame(b); channel.writeAndFlush(frame); }
public ChannelFuture write(Communication.HeshReqMessage message) { byte[] bytes = message.toByteArray(); ByteBuf b = Unpooled.buffer(bytes.length); b.writeBytes(bytes); WebSocketFrame frame = new BinaryWebSocketFrame(b); return channel.writeAndFlush(frame); }
@Override protected void decode(ChannelHandlerContext ctx,BinaryWebSocketFrame wsFrame,List<Object> out) throws Exception { ByteBuf buf = wsFrame.content(); this.messageNewDecoder.decode(ctx,buf,out); }
@Override protected void encode(ChannelHandlerContext ctx,Message msg,List<Object> out) throws Exception { if (msg == null || !(msg instanceof Message)) return; byte[] data = ((Message) msg).toBytes(); out.add(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(data))); }
/** * 将webSocket消息转换为bytebuf类型,以适配后面的解码器 */ @Override protected void decode(ChannelHandlerContext paramChannelHandlerContext,WebSocketFrame paramINBOUND_IN,List<Object> paramList) throws Exception { if(paramINBOUND_IN instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame msg=(BinaryWebSocketFrame)paramINBOUND_IN; ByteBuf data = msg.content(); paramList.add(data); data.retain(); } }
/** * 对于业务层直接发送的bytebuf实例将其转换为websocket消息 */ @Override protected void encode(ChannelHandlerContext paramChannelHandlerContext,ByteBuf paramOUTBOUND_IN,List<Object> paramList) throws Exception { paramList.add(new BinaryWebSocketFrame(paramOUTBOUND_IN)); paramOUTBOUND_IN.retain(); }
@Override public void run() { try { VersionResponse response = new VersionResponse(); response.setRequestId(this.request.getRequestId()); ctx.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(om.writeValueAsBytes(response)))); } catch (JsonProcessingException e) { LOG.error("Error serializing version response",e); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { LOG.info("Received msg: {}",msg); if (!this.handshaker.isHandshakeComplete()) { this.handshaker.finishHandshake(ctx.channel(),(FullHttpResponse) msg); LOG.info("Client connected."); this.connected = true; this.handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { throw new IllegalStateException("Unexpected response: " + msg.toString()); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { synchronized (responses) { responses.add(((TextWebSocketFrame) frame).text().getBytes(StandardCharsets.UTF_8)); } } else if (frame instanceof BinaryWebSocketFrame) { ByteBuf buf = frame.content(); byte[] b = new byte[buf.readableBytes()]; buf.readBytes(b); synchronized (responses) { responses.add(b); } } else if (frame instanceof PingWebSocketFrame) { LOG.info("Returning pong message"); ctx.writeAndFlush(new PongWebSocketFrame()); } else if (frame instanceof CloseWebSocketFrame) { LOG.info("Received message from server to close the channel."); ctx.close(); } else { LOG.warn("Unhandled frame type received: " + frame.getClass()); } }
@Override public void channelRead0(final ChannelHandlerContext ctx,WebSocketFrame frame) throws Exception { webSocketServerThread.log(Level.FInesT,"channel read,frame="+frame); // Todo: log at INFO level if this the first data we received from a client (new first connection),to // help detect clients connecting but not sending authentication commands (in newPlayer) if (this.checkIPBans) { String ip = webSocketServerThread.getRemoteIP(ctx.channel()); if (this.ipBans.contains(ip)) { webSocketServerThread.sendLine(ctx.channel(),"T,Banned from server"); // Todo: show reason,getBanList return; } } if (frame instanceof BinaryWebSocketFrame) { ByteBuf content = frame.content(); byte[] bytes = new byte[content.capacity()]; content.getBytes(0,bytes); final String string = new String(bytes); webSocketServerThread.log(Level.FInesT,"received "+content.capacity()+" bytes: "+string); this.webSocketServerThread.scheduleSyncTask(new Runnable() { @Override public void run() { webSocketServerThread.handle(string,ctx); } }); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
public void broadcastLineExcept(ChannelId excludeChannelId,String message) { for (Channel channel: allUsersGroup) { if (channel.id().equals(excludeChannelId)) { continue; } channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.copiedBuffer((message + "\n").getBytes()))); } }
@SuppressWarnings({ "unchecked","rawtypes" }) @Override protected void encode(ChannelHandlerContext ctx,List out) throws Exception { ByteBuf buf = ctx.alloc().buffer().order(ByteOrder.LITTLE_ENDIAN); int packetId = reg.CLIENTBOUND.getPacketId(packet.getClass()); if (packetId == -1) { throw new IllegalArgumentException("Provided packet is not registered as a clientbound packet!"); } buf.writeByte(packetId); packet.writeData(buf); out.add(new BinaryWebSocketFrame(buf)); Server.log.finest("Sent packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") to " + ctx.channel().remoteAddress()); }
@Override protected void decode(ChannelHandlerContext chc,BinaryWebSocketFrame frame,List<Object> out) throws Exception { //convert the frame to a ByteBuf ByteBuf bb = frame.content(); bb.retain(); out.add(bb); }
@Override protected void encode(ChannelHandlerContext chc,ByteBuf bb,List<Object> out) throws Exception { //convert the ByteBuf to a WebSocketFrame BinaryWebSocketFrame result = new BinaryWebSocketFrame(); result.content().writeBytes(bb); out.add(result); }
@SuppressWarnings({ "deprecation","unchecked",List out) throws Exception { ByteBuf buf = ctx.alloc().buffer().order(ByteOrder.BIG_ENDIAN); int packetId = PacketRegistry.CLIENTBOUND.getPacketId(packet.getClass()); if (packetId == -1) { throw new IllegalArgumentException("Provided packet is not registered as a clientbound packet!"); } buf.writeByte(packetId); packet.writeData(buf); out.add(new BinaryWebSocketFrame(buf)); ClitherServer.log.finest("Sent packet " + " (" + packet.getClass().getSimpleName() + ") to " + ctx.channel().remoteAddress()); }
io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码
@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(); } }
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); }
@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()); }
@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\",((CloseWebSocketFrame) ctx.msg).reasonText()); }
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); } } } }
@Override public void onInboundNext(ChannelHandlerContext ctx,Object frame) { if (frame instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) frame).isFinalFragment()) { if (log.isDebugEnabled()) { log.debug("CloseWebSocketFrame detected. Closing Websocket"); } CloseWebSocketFrame close = (CloseWebSocketFrame) frame; sendClose(new CloseWebSocketFrame(true,close.rsv(),close.content()),f -> onHandlerTerminate()); return; } if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) frame).content())); ctx.read(); return; } super.onInboundNext(ctx,frame); }
private Message decodeWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return null; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return null; } if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; return parseMessage(textFrame.content()); } if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; return parseMessage(binFrame.content()); } log.warn("Message format error: " + frame); return null; }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { addTraceForFrame(frame,"close"); handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { addTraceForFrame(frame,"ping"); 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())); } // todo [om] think about BinaryWebsocketFrame handleTextWebSocketFrameInternal((TextWebSocketFrame) frame,ctx); }
private void handleWebSocketFrame(ChannelHandlerContext ctx,(CloseWebSocketFrame) frame.retain()); return; } 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())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); System.err.printf("%s received %s%n",ctx.channel(),request); ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx,(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } }
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())); } }
@Override public void accept(ChannelHandlerContext ctx,WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); endpoint.releaseReferences(); endpoint.onClose(); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { endpoint.onMessage(((TextWebSocketFrame) frame).text()); return; } throw new UnsupportedOperationException(String.format("Unsupported websocket frame of type %s",frame.getClass().getName())); }
private void handlerWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // 判断是否关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } // 判断是否ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } // 仅支持文本消息,不支持二进制消息 if (!(frame instanceof TextWebSocketFrame)) { ctx.close();//(String.format("%s frame types not supported",frame.getClass().getName())); return; } }
public void handle(ChannelHandlerContext ctx,(CloseWebSocketFrame) frame); onClose(ctx); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass() .getName())); } String msg = ((TextWebSocketFrame) frame).text(); onMessage(ctx,msg); }
public void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // 判断是否是关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } // 判断是否是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(String.format("%s received %s",request)); ctx.channel().write(new TextWebSocketFrame(request+",现在时刻:"+new Date())); }
@Override public void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { Channel channel = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(channel,(FullHttpResponse) msg); handshakeFuture.setSuccess(); eventBus.post(new Connected()); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.status() + ",content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; eventBus.post(new Response(textFrame.text())); } else if (frame instanceof CloseWebSocketFrame) { channel.close(); eventBus.post(new disconnected()); } }
@Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws UnkNownWebSocketFrameTypeException,ServerConnectorException { if (!(msg instanceof WebSocketFrame)) { logger.error("Expecting WebSocketFrame. UnkNown type."); throw new UnkNownWebSocketFrameTypeException("Expecting WebSocketFrame. UnkNown type."); } if (msg instanceof TextWebSocketFrame) { notifyTextMessage((TextWebSocketFrame) msg); } else if (msg instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) msg); } else if (msg instanceof CloseWebSocketFrame) { notifyCloseMessage((CloseWebSocketFrame) msg); } else if (msg instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) msg); } else if (msg instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) msg); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,WebSocketFrame frame) throws Exception { if (frame instanceof TextWebSocketFrame) { // Echos the same text String text = ((TextWebSocketFrame) frame).text(); if (PING.equals(text)) { ctx.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{1,2,3,4}))); return; } ctx.channel().writeAndFlush(new TextWebSocketFrame(text)); } else if (frame instanceof BinaryWebSocketFrame) { ctx.channel().writeAndFlush(frame.retain()); } else if (frame instanceof CloseWebSocketFrame) { ctx.close(); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,frame.getClass() .getName())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,frame.getClass() .getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("%s received %s",request)); } ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx,request)); } ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
@Override protected void channelRead0(ChannelHandlerContext ctx,WebSocketFrame frame) throws Exception { this.last = ctx; if (frame instanceof CloseWebSocketFrame) { this.log.debug("recevied close frame"); this.server.unsubscribe(this); this.handshaker.close(ctx.channel(),(CloseWebSocketFrame)frame); } else if (frame instanceof PingWebSocketFrame) { this.log.debug("recevied ping frame"); ctx.write(new PongWebSocketFrame(frame.content())); } else if (frame instanceof TextWebSocketFrame) { this.log.debug("recevied text frame"); this.handleTextWebSocketFrame(ctx,(TextWebSocketFrame)frame); } else { this.log.info("recevied unkNown incompatible frame"); ctx.close(); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { _logger.debug("Handling websocket frame"); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { _handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } 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(); _logger.debug("{} received {}",request); _messageQueue.add(frame.content().retain()); //ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx,request)); } ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx,request)); } ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx,frame.content())); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass() .getName())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); } }
public void handle(final Object msg) { ready(); if (msg instanceof TextWebSocketFrame) { onTextCallback.accept(((TextWebSocketFrame) msg).text()); } else if (msg instanceof BinaryWebSocketFrame) { onBinaryCallback.accept(((BinaryWebSocketFrame) msg).content().nioBuffer()); } else if (msg instanceof CloseWebSocketFrame) { CloseWebSocketFrame closeFrame = ((CloseWebSocketFrame) msg).retain(); int statusCode = closeFrame.statusCode(); onCloseCallback.accept(statusCode == -1 ? WebSocket.norMAL.code() : statusCode,Optional.ofNullable(closeFrame.reasonText())); handshaker.close(ctx.channel(),closeFrame).addListener(CLOSE); } else if (msg instanceof Throwable) { onErrorCallback.accept((Throwable) msg); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof BinaryWebSocketFrame) try { this.connection.onMessage(((BinaryWebSocketFrame) frame).content().retain()); } catch (Exception e) { logger.error("onMessage error",e); handshaker.close(ctx.channel(),new CloseWebSocketFrame(true,frame.content().clear() .writeShort(1000) .writeBytes(e.getMessage().getBytes(CharsetUtil.UTF_8)) .retain())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame msg) throws Exception { if (log.isDebugEnabled()) log.debug("Received {} WebSocketFrame: {} from channel: {}",getTransportType().getName(),msg,ctx.channel()); if (msg instanceof CloseWebSocketFrame) { sessionIdByChannel.remove(ctx.channel()); ChannelFuture f = ctx.writeAndFlush(msg); f.addListener(ChannelFutureListener.CLOSE); } else if (msg instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(msg.content())); } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame){ Packet packet = PacketDecoder.decodePacket(msg.content()); packet.setTransportType(getTransportType()); String sessionId = sessionIdByChannel.get(ctx.channel()); packet.setSessionId(sessionId); msg.release(); ctx.fireChannelRead(packet); } else { msg.release(); log.warn("{} frame type is not supported",msg.getClass().getName()); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { LOG.info("Received msg: {}",msg); if (!this.handshaker.isHandshakeComplete()) { this.handshaker.finishHandshake(ctx.channel(),(FullHttpResponse) msg); LOG.info("Client connected."); this.connected = true; this.handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { throw new IllegalStateException("Unexpected response: " + msg.toString()); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { synchronized (responses) { responses.add(((TextWebSocketFrame) frame).text().getBytes(StandardCharsets.UTF_8)); } } else if (frame instanceof BinaryWebSocketFrame) { ByteBuf buf = frame.content(); byte[] b = new byte[buf.readableBytes()]; buf.readBytes(b); synchronized (responses) { responses.add(b); } } else if (frame instanceof PingWebSocketFrame) { LOG.info("Returning pong message"); ctx.writeAndFlush(new PongWebSocketFrame()); } else if (frame instanceof CloseWebSocketFrame) { LOG.info("Received message from server to close the channel."); ctx.close(); } else { LOG.warn("Unhandled frame type received: " + frame.getClass()); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ",content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; if (msg instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); } else if (msg instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } else if (msg instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } } }
/** * disconnect from the AudioConnect server and reset.<br> * If a connection is not established or being established,this will do nothing. * @return a Future for when the connection has been fully disconnected and closed */ public Future<?> disconnect() { Connection connection; synchronized (connectionLock) { connection = this.connection; this.connection = null; } if (connection != null) { playerScheduler.clear(); connection.playerConnections.clear(); // Remove channelCloseListener to not reconnect connection.channel.closeFuture().removeListener(channelCloseListener); if (connection.channel.isActive()) { final Promise<Object> disconnectPromise = bootstrap.group().next().newPromise(); Object closeFrame = new CloseWebSocketFrame(WEBSOCKET_CLOSE_CODE_GOING_AWAY,"Going offline"); connection.channel.writeAndFlush(closeFrame).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { future.channel().close().addListener(new PromiseNotifier<>(disconnectPromise)); } }); return disconnectPromise; } } return bootstrap.group().next().newSucceededFuture(null); }
@Override protected void channelRead0(ChannelHandlerContext ctx,AddSubscription add) throws Exception { Subscription s = SubscriptionRegistry.get().get(add.getSubscriptionId()); if (null != s) { String metric = add.getMetric(); if (null == metric) { LOG.error("Metric name cannot be null in add subscription"); ctx.writeAndFlush(new CloseWebSocketFrame(1008,"Metric name cannot be null in add subscription")); } Map<String,String> tags = null; Long startTime = 0L; Long endTime = 0L; Long delayTime = 5000L; if (add.getTags().isPresent()) { tags = add.getTags().get(); } if (add.getStartTime().isPresent()) { startTime = add.getStartTime().get(); } if (add.getEndTime().isPresent()) { endTime = add.getEndTime().get(); } if (add.getDelayTime().isPresent()) { delayTime = add.getDelayTime().get(); } s.addMetric(metric,tags,startTime,endTime,delayTime); } else { LOG.error("UnkNown subscription id,create subscription first"); ctx.writeAndFlush(new CloseWebSocketFrame(1003,"UnkNown subscription id,create subscription first")); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,CloseSubscription close) throws Exception { Subscription s = SubscriptionRegistry.get().remove(close.getSubscriptionId()); if (null != s) { s.close(); } ctx.writeAndFlush(new CloseWebSocketFrame(1000,"Client requested close.")); }
@Override protected void channelRead0(ChannelHandlerContext ctx,QueryRequest msg) throws Exception { try { String response = JsonUtil.getobjectMapper().writeValueAsstring(dataStore.query(msg)); ctx.writeAndFlush(new TextWebSocketFrame(response)); } catch (TimelyException e) { if (e.getMessage().contains("No matching tags")) { LOG.trace(e.getMessage()); } else { LOG.error(e.getMessage(),e); } ctx.writeAndFlush(new CloseWebSocketFrame(1008,e.getMessage())); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,SuggestRequest msg) throws Exception { try { String response = JsonUtil.getobjectMapper().writeValueAsstring(dataStore.suggest(msg)); ctx.writeAndFlush(new TextWebSocketFrame(response)); } catch (TimelyException e) { LOG.error(e.getMessage(),e); ctx.writeAndFlush(new CloseWebSocketFrame(1008,e.getMessage())); } }
@Override protected void channelRead0(ChannelHandlerContext ctx,SearchLookupRequest msg) throws Exception { try { String response = JsonUtil.getobjectMapper().writeValueAsstring(dataStore.lookup(msg)); ctx.writeAndFlush(new TextWebSocketFrame(response)); } catch (TimelyException e) { LOG.error(e.getMessage(),e.getMessage())); } }
@Test public void testCreateSubscriptionWithoutSubscriptionId() throws Exception { decoder = new WebSocketRequestDecoder(anonConfig); String request = "{ \"operation\" : \"create\" }"; TextWebSocketFrame frame = new TextWebSocketFrame(); frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8)); decoder.decode(ctx,((CloseWebSocketFrame) ctx.msg).statusCode()); Assert.assertEquals("Subscription ID is required.",((CloseWebSocketFrame) ctx.msg).reasonText()); }
关于javax.websocket.Decoder.TextStream的实例源码和java socket源码的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于com.facebook.react.bridge.WebsocketJavaScriptExecutor的实例源码、com.facebook.react.modules.websocket.WebSocketModule的实例源码、io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码的相关知识,请在本站寻找。
本文标签: