本篇文章给大家谈谈javax.websocket.Endpoint的实例源码,以及javawebsocketclient的知识点,同时本文还将给你拓展io.netty.handler.codec.ht
本篇文章给大家谈谈javax.websocket.Endpoint的实例源码,以及java websocketclient的知识点,同时本文还将给你拓展io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker的实例源码、java WebSocket的实现以及Spring WebSocket示例代码等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:- javax.websocket.Endpoint的实例源码(java websocketclient)
- io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码
- io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码
- io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker的实例源码
- java WebSocket的实现以及Spring WebSocket示例代码
javax.websocket.Endpoint的实例源码(java websocketclient)
protected void registerSession(Endpoint endpoint,WsSession wsSession) { if (!wsSession.isopen()) { // The session was closed during onopen. No need to register it. return; } synchronized (endPointSessionMapLock) { if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().register(this); } Set<WsSession> wsSessions = endpointSessionMap.get(endpoint); if (wsSessions == null) { wsSessions = new HashSet<WsSession>(); endpointSessionMap.put(endpoint,wsSessions); } wsSessions.add(wsSession); } sessions.put(wsSession,wsSession); }
protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpoint); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpoint); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); }
private void initWebSocketSession(String url,int wsConnectionTimeout) throws Exception { CountDownLatch wsLatch = new CountDownLatch(1); ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); ClientManager client = ClientManager.createClient(); client.connectToServer(new Endpoint() { @Override public void onopen(Session session,EndpointConfig endpointConfig) { wsSession = session; wsLatch.countDown(); } },cec,new URI(url)); if (!wsLatch.await(wsConnectionTimeout,TimeUnit.SECONDS)) { throw new TimeoutException("Web socket connection timeout"); } }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>(); if (scanned.contains(EchoEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( EchoEndpoint.class,"/websocket/echoProgrammatic").build()); } if (scanned.contains(DrawboardEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( DrawboardEndpoint.class,"/websocket/drawboard").build()); } return result; }
protected void registerSession(Endpoint endpoint,wsSession); }
protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpoint); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpoint); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); }
protected void registerSession(Endpoint endpoint,wsSession); }
protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpoint); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpoint); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); }
@Override protected void openConnection() { this.taskExecutor.execute(new Runnable() { @Override public void run() { try { logger.info("Connecting to WebSocket at " + getUri()); Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); ClientEndpointConfig endpointConfig = configBuilder.build(); session = getWebSocketContainer().connectToServer(endpointToUse,endpointConfig,getUri()); logger.info("Successfully connected"); } catch (Throwable ex) { logger.error("Failed to connect",ex); } } }); }
@Override public void upgradeInternal(ServerHttpRequest httpRequest,ServerHttpResponse httpResponse,String selectedProtocol,List<Extension> selectedExtensions,Endpoint endpoint) throws HandshakeFailureException { HttpServletRequest request = getHttpServletRequest(httpRequest); HttpServletResponse response = getHttpServletResponse(httpResponse); StringBuffer requestUrl = request.getRequestURL(); String path = request.getRequestURI(); // shouldn't matter Map<String,String> pathParams = Collections.<String,String> emptyMap(); ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path,endpoint); endpointConfig.setSubprotocols(Collections.singletonList(selectedProtocol)); endpointConfig.setExtensions(selectedExtensions); try { ServerContainer container = getContainer(request); upgradeMethod.invoke(container,request,response,pathParams); } catch (Exception ex) { throw new HandshakeFailureException( "Servlet request Failed to upgrade to WebSocket for " + requestUrl,ex); } }
private ConfiguredServerEndpoint createConfiguredServerEndpoint(String selectedProtocol,Endpoint endpoint,HttpServletRequest servletRequest) { String path = servletRequest.getRequestURI(); // shouldn't matter ServerEndpointRegistration endpointRegistration = new ServerEndpointRegistration(path,endpoint); endpointRegistration.setSubprotocols(Arrays.asList(selectedProtocol)); endpointRegistration.setExtensions(selectedExtensions); EncodingFactory encodingFactory = new EncodingFactory( Collections.<Class<?>,List<InstanceFactory<? extends Encoder>>>emptyMap(),Collections.<Class<?>,List<InstanceFactory<? extends Decoder>>>emptyMap(),List<InstanceFactory<? extends Decoder>>>emptyMap()); try { return (endpointConstructorWithEndpointFactory ? endpointConstructor.newInstance(endpointRegistration,new EndpointInstanceFactory(endpoint),null,encodingFactory,null) : endpointConstructor.newInstance(endpointRegistration,encodingFactory)); } catch (Exception ex) { throw new HandshakeFailureException("Failed to instantiate ConfiguredServerEndpoint",ex); } }
@Test public void testCreateWebSocketAndConnectToServer() throws Exception { SlackWebsocketConnection slack = new SlackWebsocketConnection("token",8080); SlackAuthen slackAuthen = powermockito.mock(SlackAuthen.class); powermockito.whenNew(SlackAuthen.class).withNoArguments().thenReturn(slackAuthen); powermockito.when(slackAuthen.tokenAuthen(Mockito.anyString(),Mockito.anyString(),Mockito.anyInt())).thenReturn(slackInfo); ClientManager clientManager = powermockito.mock(ClientManager.class); powermockito.mockStatic(ClientManager.class); powermockito.when(ClientManager.createClient()).thenReturn(clientManager); boolean connect = slack.connect(); assertthat(connect,is(true)); Mockito.verify(clientManager).connectToServer(Mockito.any(Endpoint.class),Mockito.any(URI.class)); powermockito.verifyStatic(); ClientManager.createClient(); }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<>(); // Endpoint subclass config if (scanned.contains(MyEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( MyEndpoint.class,"/MyEndpoint").build()); } if (scanned.contains(GameEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( GameEndpoint.class,"/Game").build()); } return result; }
/** * Create session * * @param jsessionid * @param userpwd * @return */ protected Session createAndGetSession(String jsessionid,String userpwd) { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { StringBuilder sb = new StringBuilder("ws://localhost:"); sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append("ocelot-endpoint"); URI uri = new URI(sb.toString()); return container.connectToServer(new Endpoint() { @Override public void onopen(Session session,EndpointConfig config) { } },createClientEndpointConfigWithJsession(jsessionid,userpwd),uri); } catch (URISyntaxException | DeploymentException | IOException ex) { ex.getCause().printstacktrace(); fail("CONNEXION Failed " + ex.getMessage()); } return null; }
private void assertMessageReceived( String endpoint,String expectedMessage,String messagetoSend ) throws Exception { final SettableFuture<String> futureMessage = SettableFuture.create(); client.connectToServer( new Endpoint() { @Override public void onopen( Session session,EndpointConfig config ) { clientSession = session; try { session.addMessageHandler( new MessageHandler.Whole<String>() { @Override public void onMessage( String message ) { System.out.println( "Received message: " + message ); futureMessage.set( message ); } } ); session.getBasicRemote().sendText( messagetoSend ); } catch ( IOException e ) { e.printstacktrace(); } } },new URI( "ws://localhost:8025/" + endpoint ) ); assertEquals( expectedMessage,futureMessage.get( 2,TimeUnit.SECONDS ) ); }
protected void registerSession(Endpoint endpoint,WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); if (!wsSession.isopen()) { // The session was closed during onopen. No need to register it. return; } synchronized (endPointSessionMapLock) { if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().register(this); } Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions == null) { wsSessions = new HashSet<WsSession>(); endpointSessionMap.put(endpointClazz,wsSession); }
protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpointClazz); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>(); if (scanned.contains(EchoEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( EchoEndpoint.class,"/websocket/drawboard").build()); } return result; }
@Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> set) { return new HashSet<ServerEndpointConfig>() {{ add(ServerEndpointConfig.Builder .create(MyEndpoint.class,"/websocket") .configurator(new ServerEndpointConfig.Configurator() { @Override public void modifyHandshake(ServerEndpointConfig sec,HandshakeRequest request,HandshakeResponse response) { HttpSession session = (HttpSession)request.getHttpSession(); System.out.println("HttpSession id: " + session.getId()); System.out.println("HttpSession creation time: " + session.getCreationTime()); super.modifyHandshake(sec,response); } }) .build()); }}; }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>(); if (scanned.contains(EchoEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( EchoEndpoint.class,"/websocket/drawboard").build()); } return result; }
protected void registerSession(Endpoint endpoint,wsSession); }
protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpointClazz); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); }
@Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>(); if (scanned.contains(EchoEndpoint.class)) { result.add(ServerEndpointConfig.Builder.create( EchoEndpoint.class,"/websocket/drawboard").build()); } return result; }
@Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> set) { Set<ServerEndpointConfig> sets = new HashSet<>(); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(ProgrammaticServer.class,WS_PATH) .configurator(new HttpSessionConfigurator()) .build(); sets.add(config); return sets; }
Set<Session> getopenSessions(Endpoint endpoint) { HashSet<Session> result = new HashSet<Session>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; }
public void preInit(Endpoint ep,EndpointConfig endpointConfig,WsServerContainer wsc,WsHandshakeRequest handshakeRequest,List<Extension> negotiatedExtensionsPhase2,String subProtocol,Transformation transformation,Map<String,String> pathParameters,boolean secure) { this.ep = ep; this.endpointConfig = endpointConfig; this.webSocketContainer = wsc; this.handshakeRequest = handshakeRequest; this.negotiatedExtensions = negotiatedExtensionsPhase2; this.subProtocol = subProtocol; this.transformation = transformation; this.pathParameters = pathParameters; this.secure = secure; }
/** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void registerSession(Endpoint endpoint,WsSession wsSession) { super.registerSession(endpoint,wsSession); if (wsSession.isopen() && wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) { registerauthenticatedSession(wsSession,wsSession.getHttpSessionId()); } }
/** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { if (wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) { unregisterauthenticatedSession(wsSession,wsSession.getHttpSessionId()); } super.unregisterSession(endpoint,wsSession); }
Set<Session> getopenSessions(Endpoint endpoint) { HashSet<Session> result = new HashSet<Session>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; }
public void preInit(Endpoint ep,boolean secure) { this.ep = ep; this.endpointConfig = endpointConfig; this.webSocketContainer = wsc; this.handshakeRequest = handshakeRequest; this.negotiatedExtensions = negotiatedExtensionsPhase2; this.subProtocol = subProtocol; this.transformation = transformation; this.pathParameters = pathParameters; this.secure = secure; }
/** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void registerSession(Endpoint endpoint,wsSession.getHttpSessionId()); } }
/** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void unregisterSession(Endpoint endpoint,wsSession); }
Set<Session> getopenSessions(Endpoint endpoint) { HashSet<Session> result = new HashSet<Session>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; }
public void preInit(Endpoint ep,boolean secure) { this.ep = ep; this.endpointConfig = endpointConfig; this.webSocketContainer = wsc; this.handshakeRequest = handshakeRequest; this.negotiatedExtensions = negotiatedExtensionsPhase2; this.subProtocol = subProtocol; this.transformation = transformation; this.pathParameters = pathParameters; this.secure = secure; }
/** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void registerSession(Endpoint endpoint,wsSession); if (wsSession.isopen() && wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) { registerauthenticatedSession(wsSession,wsSession.getHttpSessionId()); } }
/** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void unregisterSession(Endpoint endpoint,WsSession wsSession) { if (wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) { unregisterauthenticatedSession(wsSession,wsSession); }
io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码
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); }
public Subscription(String subscriptionId,String sessionId,DataStore store,ChannelHandlerContext ctx,Configuration conf) { this.subscriptionId = subscriptionId; this.sessionId = sessionId; this.store = store; this.ctx = ctx; this.lag = conf.getWebsocket().getSubscriptionLag(); this.scannerBatchSize = conf.getWebsocket().getScannerBatchSize(); this.flushIntervalSeconds = conf.getWebsocket().getFlushIntervalSeconds(); this.scannerReadAhead = conf.getWebsocket().getScannerReadAhead(); this.subscriptionBatchSize = conf.getWebsocket().getSubscriptionBatchSize(); // send a websocket ping at half the timeout interval. int rate = conf.getWebsocket().getTimeout() / 2; this.ping = this.ctx.executor().scheduleAtFixedrate(() -> { LOG.trace("Sending ping on channel {}",ctx.channel()); ctx.writeAndFlush(new PingWebSocketFrame()); cleanupCompletedMetrics(); },rate,TimeUnit.SECONDS); }
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); }
@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.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 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()); } }
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,(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()); } } 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()); } }
/** * Send a ping message to the server. * * @param buf content of the ping message to be sent. */ public void sendPing(ByteBuffer buf) throws IOException { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new IllegalArgumentException("Cannot find the channel to write"); } channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf))); }
protected void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { logger.debug("Received incoming frame [{}]",frame.getClass().getName()); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { if (frameBuffer != null) { handleMessageCompleted(ctx,frameBuffer.toString()); } handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof PongWebSocketFrame) { logger.info("Pong frame received"); return; } if (frame instanceof TextWebSocketFrame) { frameBuffer = new StringBuilder(); frameBuffer.append(((TextWebSocketFrame)frame).text()); } else if (frame instanceof ContinuationWebSocketFrame) { if (frameBuffer != null) { frameBuffer.append(((ContinuationWebSocketFrame)frame).text()); } else { logger.warn("Continuation frame received without initial frame."); } } else { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass().getName())); } // Check if Text or Continuation Frame is final fragment and handle if needed. if (frame.isFinalFragment()) { handleMessageCompleted(ctx,frameBuffer.toString()); frameBuffer = null; } }
private 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(); if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("%s received %s",request)); } ctx.channel().write( new TextWebSocketFrame(request + ",欢迎使用Netty WebSocket服务,现在时刻:" + new java.util.Date().toString())); }
/** * Send a ping message to the server. * @param buf content of the ping message to be sent. */ public void sendPing(ByteBuffer buf) throws IOException { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new IllegalArgumentException("Cannot find the channel to write"); } channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf))); }
private void notifyPingMessage(PingWebSocketFrame pingWebSocketFrame) throws ServerConnectorException { //Control message for WebSocket is Ping Message ByteBuf byteBuf = pingWebSocketFrame.content(); ByteBuffer byteBuffer = byteBuf.nioBuffer(); WebSocketMessageImpl webSocketControlMessage = new WebSocketControlMessageImpl(WebSocketControlSignal.PING,byteBuffer); webSocketControlMessage = setupCommonProperties(webSocketControlMessage); connectorFuture.notifyWSListener((WebSocketControlMessage) webSocketControlMessage); }
@Override public void channelRead0(ChannelHandlerContext ctx,URISyntaxException,ServerConnectorException { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); log.debug("WebSocket Client connected!"); handshakeFuture.setSuccess(); channelSession = WebSocketUtil.getSession(ctx,isSecure,requestedUri); 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) { notifyTextMessage((TextWebSocketFrame) frame,ctx); } else if (frame instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) frame,ctx); } else if (frame instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) frame,ctx); } else if (frame instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) frame,ctx); } else if (frame instanceof CloseWebSocketFrame) { if (channelSession != null) { channelSession.setIsOpen(false); } notifyCloseMessage((CloseWebSocketFrame) frame,ctx); ch.close(); } else { throw new UnkNownWebSocketFrameTypeException("Cannot identify the WebSocket frame type"); } }
private void notifyPingMessage(PingWebSocketFrame pingWebSocketFrame,ChannelHandlerContext ctx) throws ServerConnectorException { //Control message for WebSocket is Ping Message ByteBuf byteBuf = pingWebSocketFrame.content(); ByteBuffer byteBuffer = byteBuf.nioBuffer(); WebSocketMessageImpl webSocketControlMessage = new WebSocketControlMessageImpl(WebSocketControlSignal.PING,byteBuffer); webSocketControlMessage = setupCommonProperties(webSocketControlMessage,ctx); connectorListener.onMessage((WebSocketControlMessage) webSocketControlMessage); }
/** * Send a ping message to the server. * @param buf content of the ping message to be sent. */ public void sendPing(ByteBuffer buf) throws IOException { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new IllegalArgumentException("Cannot find the channel to write"); } channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf))); }
private boolean handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { this.handshaker.close(ctx.channel(),((CloseWebSocketFrame) frame).retain()); return false; } else if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return false; } else if (!(frame instanceof TextWebSocketFrame) && !(frame instanceof BinaryWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass().getName())); } return true; }
private void handleWebSocketFrame(ChannelHandlerContext ctx,frame.getClass() .getName())); } // Send the uppercase string back. TextWebSocketFrame frame2 = (TextWebSocketFrame) frame; String request = frame2.text(); Thread t = Thread.currentThread(); System.err.printf("%s received %s%n thread %d ",request,t.getId()); /////////////////// //Do your work here /////////////////// ctx.channel().write(new TextWebSocketFrame(request.toupperCase())); }
io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码
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); }
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); }
@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.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 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); } }
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()); } }
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(); } } }
@Override protected void channelRead0(ChannelHandlerContext ctx,(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()); } } 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(final ChannelHandlerContext ctx,final Object msg) throws Exception { final Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { // web socket client connected handshaker.finishHandshake(ch,(FullHttpResponse) msg); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ",content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } // a close frame doesn't mean much here. errors raised from closed channels will mark the host as dead final WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { ctx.fireChannelRead(frame.retain(2)); } else if (frame instanceof PongWebSocketFrame) { } else if (frame instanceof BinaryWebSocketFrame) { ctx.fireChannelRead(frame.retain(2)); } else if (frame instanceof CloseWebSocketFrame) ch.close(); }
@Override public void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); handshakeFuture.setSuccess(); //connection is opened. client.onopen(handshaker); 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; client.onMessage(textFrame.text()); } else if (frame instanceof PongWebSocketFrame) { /* * placeholder. maybe add onPong method to the RhinoClient */ } else if (frame instanceof CloseWebSocketFrame) { client.onClose(); ch.close(); } }
@Override public 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.status() + ",content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); } else if (frame instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } }
protected void handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { logger.debug("Received incoming frame [{}]",frame.getClass().getName()); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { if (frameBuffer != null) { handleMessageCompleted(ctx,frameBuffer.toString()); } handshaker.close(ctx.channel(),(CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof PongWebSocketFrame) { logger.info("Pong frame received"); return; } if (frame instanceof TextWebSocketFrame) { frameBuffer = new StringBuilder(); frameBuffer.append(((TextWebSocketFrame)frame).text()); } else if (frame instanceof ContinuationWebSocketFrame) { if (frameBuffer != null) { frameBuffer.append(((ContinuationWebSocketFrame)frame).text()); } else { logger.warn("Continuation frame received without initial frame."); } } else { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass().getName())); } // Check if Text or Continuation Frame is final fragment and handle if needed. if (frame.isFinalFragment()) { handleMessageCompleted(ctx,frameBuffer.toString()); frameBuffer = null; } }
private 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(); if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("%s received %s",request)); } ctx.channel().write( new TextWebSocketFrame(request + ",欢迎使用Netty WebSocket服务,现在时刻:" + new java.util.Date().toString())); }
@Override public void channelRead0(ChannelHandlerContext ctx,(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) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); } else if (frame instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } }
@Override public void channelRead0(ChannelHandlerContext ctx,(FullHttpResponse) msg); logger.debug("WebSocket Client connected!"); handshakeFuture.setSuccess(); 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; logger.debug("WebSocket Client received text message: " + textFrame.text()); textReceived = textFrame.text(); } else if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame; bufferReceived = binaryFrame.content().nioBuffer(); logger.debug("WebSocket Client received binary message: " + bufferReceived.toString()); } else if (frame instanceof PongWebSocketFrame) { logger.debug("WebSocket Client received pong"); PongWebSocketFrame pongFrame = (PongWebSocketFrame) frame; bufferReceived = pongFrame.content().nioBuffer(); } else if (frame instanceof CloseWebSocketFrame) { logger.debug("WebSocket Client received closing"); ch.close(); } }
private void notifyPongMessage(PongWebSocketFrame pongWebSocketFrame) throws ServerConnectorException { //Control message for WebSocket is Pong Message ByteBuf byteBuf = pongWebSocketFrame.content(); ByteBuffer byteBuffer = byteBuf.nioBuffer(); WebSocketMessageImpl webSocketControlMessage = new WebSocketControlMessageImpl(WebSocketControlSignal.PONG,byteBuffer); webSocketControlMessage = setupCommonProperties(webSocketControlMessage); connectorFuture.notifyWSListener((WebSocketControlMessage) webSocketControlMessage); }
@Override public void channelRead0(ChannelHandlerContext ctx,URISyntaxException,ServerConnectorException { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch,(FullHttpResponse) msg); log.debug("WebSocket Client connected!"); handshakeFuture.setSuccess(); channelSession = WebSocketUtil.getSession(ctx,isSecure,requestedUri); 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) { notifyTextMessage((TextWebSocketFrame) frame,ctx); } else if (frame instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) frame,ctx); } else if (frame instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) frame,ctx); } else if (frame instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) frame,ctx); } else if (frame instanceof CloseWebSocketFrame) { if (channelSession != null) { channelSession.setIsOpen(false); } notifyCloseMessage((CloseWebSocketFrame) frame,ctx); ch.close(); } else { throw new UnkNownWebSocketFrameTypeException("Cannot identify the WebSocket frame type"); } }
private void notifyPongMessage(PongWebSocketFrame pongWebSocketFrame,ChannelHandlerContext ctx) throws ServerConnectorException { //Control message for WebSocket is Pong Message ByteBuf byteBuf = pongWebSocketFrame.content(); ByteBuffer byteBuffer = byteBuf.nioBuffer(); WebSocketMessageImpl webSocketControlMessage = new WebSocketControlMessageImpl(WebSocketControlSignal.PONG,byteBuffer); webSocketControlMessage = setupCommonProperties(webSocketControlMessage,ctx); connectorListener.onMessage((WebSocketControlMessage) webSocketControlMessage); }
private boolean handleWebSocketFrame(ChannelHandlerContext ctx,WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { this.handshaker.close(ctx.channel(),((CloseWebSocketFrame) frame).retain()); return false; } else if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return false; } else if (!(frame instanceof TextWebSocketFrame) && !(frame instanceof BinaryWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported",frame.getClass().getName())); } return true; }
io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker的实例源码
@Override protected void initChannel(SocketChannel channel) throws SSLException { URI uri = config.getConnectionWebsocketUri(); DefaultHttpHeaders headers = new DefaultHttpHeaders(); headers.add(USER_ID_HEADER,config.getConnectionUserId().toString()); headers.add(USER_PASSWORD_HEADER,config.getConnectionUserPassword()); headers.add(supplier_ID_HEADER,config.getConnectionServerId()); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,WS_VERSION,null,false,headers); ChannelPipeline pipeline = channel.pipeline(); if (config.isConnectionSecure()) { try { SslContext sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); pipeline.addLast(sslContext.newHandler(channel.alloc())); } catch (SSLException e) { logger.log(Level.SEVERE,"Shutting down client due to unexpected failure to create SSL context",e); throw e; } } pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(8192)); pipeline.addLast(new AudioConnectClientHandler(handshaker)); }
@Before public void setup() throws Exception { s = new Server(conf); s.run(); Connector con = mac.getConnector("root","secret"); con.securityOperations().changeUserAuthorizations("root",new Authorizations("A","B","C","D","E","F")); this.sessionId = UUID.randomUUID().toString(); AuthCache.getCache().put(sessionId,token); group = new NioEventLoopGroup(); SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME,sessionId); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(Names.COOKIE,cookieVal); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,WebSocketVersion.V13,(String) null,headers); handler = new ClientHandler(handshaker); Bootstrap boot = new Bootstrap(); boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("ssl",ssl.newHandler(ch.alloc(),"127.0.0.1",WS_PORT)); ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(new HttpObjectAggregator(8192)); ch.pipeline().addLast(handler); } }); ch = boot.connect("127.0.0.1",WS_PORT).sync().channel(); // Wait until handshake is complete while (!handshaker.isHandshakeComplete()) { sleepUninterruptibly(500,TimeUnit.MILLISECONDS); LOG.debug("Waiting for Handshake to complete"); } }
@Before public void setup() throws Exception { s = new Server(conf); s.run(); Connector con = mac.getConnector("root",TimeUnit.MILLISECONDS); LOG.debug("Waiting for Handshake to complete"); } }
public WebSocketTargetHandler(WebSocketClientHandshaker handshaker,boolean isSecure,String requestedUri,String target,WebSocketConnectorListener webSocketConnectorListener) { this.handshaker = handshaker; this.isSecure = isSecure; this.requestedUri = requestedUri; this.target = target; this.connectorListener = webSocketConnectorListener; handshakeFuture = null; }
@Override public void addToPipeline(final ChannelPipeline pipeline) { pipeline.addLast("http-codec",new HttpClientCodec()); pipeline.addLast("aggregator",new HttpObjectAggregator(8192)); final WebSocketClientHandshaker handShaker = new WhiteSpaceInPathWebSocketClientHandshaker13(serverUri,PROTOCOL,createHttpHeaders(httpHeaders),Integer.MAX_VALUE); pipeline.addLast("websocket-protocol-handler",new WebSocketClientProtocolHandler(handShaker)); pipeline.addLast("websocket-frame-codec",new ByteBufToWebSocketFrameCodec()); }
public WebSocketClientHandler(long uid,WebSocketClientHandshaker handshaker) { this.uid = uid; this.handshaker = handshaker; }
public ClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
private AudioConnectClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public ClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
MeetupWebSocketClientHandler(WebSocketClientHandshaker handshaker,RSVPProducer rsvpProducer) { this.handshaker = handshaker; this.rsvpProducer = rsvpProducer; }
public WebSocketClientHandler(final WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker,CountDownLatch latch) { this.handshaker = handshaker; this.latch = latch; this.isOpen = true; }
@Override public void onopen(WebSocketClientHandshaker handShaker) { // Todo Auto-generated method stub }
@Override public void onopen(WebSocketClientHandshaker handShaker) { logger.log(Level.INFO,"onopen"); }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public MessageReceiverWebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public MessageSenderWebSocketClientHandler(WebSocketClientHandshaker handshaker,String id) { this.handshaker = handshaker; publisherId = id; }
public WebSocketClientHandlerControl(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { mHandshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
@Override public void connect(WsClient client) { if (client == null) { throw new NullPointerException("client"); } final URLInfo url = client.getUrl(); String full = url.protocol + "://" + url.host + ":" + url.port + url.path; URI uri; try { uri = new URI(full); } catch (URISyntaxException e) { throw new RuntimeException(e); } WebSocketVersion v = WebSocketVersion.V13; HttpHeaders h = new DefaultHttpHeaders(); final WebSocketClientHandshaker wsch = WebSocketClientHandshakerFactory .newHandshaker(uri,v,true,h,Integer.MAX_VALUE); final WebSocketHandler handler = new WebSocketHandler(wsch,client); Bootstrap b = new Bootstrap(); b.group(Sharedobjects.getLoop()); b.channel(NioSocketChannel.class); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (url.secure) { TrustManagerFactory man = InsecureTrustManagerFactory.INSTANCE; SslContext con = SslContext.newClientContext(man); p.addLast(con.newHandler(ch.alloc())); } p.addLast(new HttpClientCodec()); p.addLast(new HttpObjectAggregator(8192)); p.addLast(handler); } }); ChannelFuture fut = b.connect(url.host,url.port); fut.syncUninterruptibly(); handler.handshakeFuture().syncUninterruptibly(); }
public WebSocketHandler(WebSocketClientHandshaker handshake,WsClient client) { this.handshake = handshake; this.client = client; }
@Override public void connect(String url) throws Exception { URI uri = new URI(url); setConnected(false); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { Notifications.Bus.notify( new Notification( "Websocket Client","Unable to connect","Only WS(S) is supported.",NotificationType.ERROR) ); return; } EventLoopGroup group = new NioEventLoopGroup(); try { WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri,new DefaultHttpHeaders()); WebSocketClientHandler webSocketClientHandler = new WebSocketClientHandler(handshaker); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast( new HttpClientCodec(),new HttpObjectAggregator(8192),webSocketClientHandler); } }); channel = bootstrap.connect(uri.getHost(),port).sync().channel(); webSocketClientHandler.handshakeFuture().sync(); setConnected(true); for (; ; ); } finally { group.shutdownGracefully(); setConnected(false); } }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; this.eventBus = EventBusService.getInstance(); }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker,CountDownLatch latch) { this.handshaker = handshaker; this.latch = latch; this.isOpen = true; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(final WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public AbstractJsonRpcWebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
public JsonRpcWebSocketClientHandler(WebSocketClientHandshaker handshaker) { super(handshaker); }
public WebsocketProtostuffEncoder(WebSocketClientHandshaker handShaker) { this.handShaker = handShaker; }
public WebSocketClientHandshaker getHandShaker() { return handShaker; }
public WebsocketProtostuffDecoder(WebSocketClientHandshaker handShaker) { super(handShaker); this.handShaker = handShaker; }
public C5ConnectionInitializer(WebSocketClientHandshaker handShaker) { super(); this.handShaker = handShaker; }
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; }
java WebSocket的实现以及Spring WebSocket示例代码
开始学习WebSocket,准备用它来实现一个在页面实时输出log4j的日志以及控制台的日志。
首先知道一些基础信息:
1.java7 开始支持WebSocket,并且只是做了定义,并未实现
2.tomcat7及以上,jetty 9.1及以上实现了WebSocket,其他容器没有研究
3.spring 4.0及以上增加了WebSocket的支持
4.spring 支持STOMP协议的WebSocket通信
5.WebSocket 作为java的一个扩展,它属于javax包目录下,通常需要手工引入该jar,以tomcat为例,可以在 tomcat/lib 目录下找到 websocket-api.jar
开始实现
先写一个普通的WebSocket客户端,直接引入tomcat目录下的jar,主要的jar有:websocket-api.jar、tomcat7-websocket.jar
public static void f1() { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 获取WebSocket连接器,其中具体实现可以参照websocket-api.jar的源码,Class.forName("org.apache.tomcat.websocket.WsWebSocketContainer"); String uri = "ws://localhost:8081/log/log"; Session session = container.connectToServer(Client.class,new URI(uri)); // 连接会话 session.getBasicRemote().sendText("123132132131"); // 发送文本消息 session.getBasicRemote().sendText("4564546"); } catch (Exception e) { e.printstacktrace(); } }
其中的URL格式必须是ws开头,后面接注册的WebSocket地址
Client.java 是用于收发消息
@ClientEndpoint public class Client { @Onopen public void onopen(Session session) { System.out.println("Connected to endpoint: " + session.getBasicRemote()); } @OnMessage public void onMessage(String message) { System.out.println(message); } @OnError public void onError(Throwable t) { t.printstacktrace(); } }
到这一步,客户端的收发消息已经完成,现在开始编写服务端代码,用Spring 4.0,其中pom.xml太长就不贴出来了,会用到jackson,spring-websocket,spring-message
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import com.gionee.log.client.LogWebSocketHandler; /** * 注册普通WebScoket * @author PengBin * @date 2016年6月21日 下午5:29:00 */ @Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Autowired @Lazy private SimpMessagingTemplate template; /** {@inheritDoc} */ @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(logWebSocketHandler(),"/log"); // 此处与客户端的 URL 相对应 } @Bean public WebSocketHandler logWebSocketHandler() { return new LogWebSocketHandler(template); } }
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; /** * * @author PengBin * @date 2016年6月24日 下午6:04:39 */ public class LogWebSocketHandler extends TextWebSocketHandler { private SimpMessagingTemplate template; public LogWebSocketHandler(SimpMessagingTemplate template) { this.template = template; System.out.println("初始化 handler"); } @Override protected void handleTextMessage(WebSocketSession session,TextMessage message) throws Exception { String text = message.getPayload(); // 获取提交过来的消息 System.out.println("handMessage:" + text); // template.convertAndSend("/topic/getLog",text); // 这里用于广播 session.sendMessage(message); } }
这样,一个普通的WebSocket就完成了,自己还可以集成安全控制等等
Spring还支持一种注解的方式,可以实现订阅和广播,采用STOMP格式协议,类似MQ,其实应该就是用的MQ的消息格式,下面是实现
同样客户端:
public static void main(String[] args) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = "ws://localhost:8081/log/hello/hello/websocket"; Session session = container.connectToServer(Client.class,new URI(uri)); char lf = 10; // 这个是换行 char nl = 0; // 这个是消息结尾的标记,一定要 StringBuilder sb = new StringBuilder(); sb.append("SEND").append(lf); // 请求的命令策略 sb.append("destination:/app/hello").append(lf); // 请求的资源 sb.append("content-length:14").append(lf).append(lf); // 消息体的长度 sb.append("{\"name\":\"123\"}").append(nl); // 消息体 session.getBasicRemote().sendText(sb.toString()); // 发送消息 Thread.sleep(50000); // 等待一小会 session.close(); // 关闭连接 } catch (Exception e) { e.printstacktrace(); } }
这里一定要注意,换行符和结束符号,这个是STOMP协议规定的符号,错了就不能解析到
服务端配置
/** * 启用STOMP协议WebSocket配置 * @author PengBin * @date 2016年6月24日 下午5:59:42 */ @Configuration @EnableWebMvc @EnableWebSocketMessagebroker public class WebSocketbrokerConfig extends AbstractWebSocketMessagebrokerConfigurer { /** {@inheritDoc} */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { System.out.println("注册"); registry.addEndpoint("/hello").withSockJS(); // 注册端点,和普通服务端的/log一样的 // withSockJS()表示支持socktJS访问,在浏览器中使用 } /** {@inheritDoc} */ @Override public void configureMessagebroker(MessagebrokerRegistry config) { System.out.println("启动"); config.enableSimplebroker("/topic"); // config.setApplicationDestinationPrefixes("/app"); // 格式前缀 } } Controller @Controller public class LogController { private SimpMessagingTemplate template; @Autowired public LogController(SimpMessagingTemplate template) { System.out.println("init"); this.template = template; } @MessageMapping("/hello") @SendTo("/topic/greetings") // 订阅 public Greeting greeting(HelloMessage message) throws Exception { System.out.println(message.getName()); Thread.sleep(3000); // simulated delay return new Greeting("Hello," + message.getName() + "!"); } }
到这里就已经全部完成。
template.convertAndSend("/topic/greetings","通知"); // 这个的意思就是向订阅了/topic/greetings进行广播
对于用socktJS连接的时候会有一个访问 /info 地址的请求
如果在浏览器连接收发送消息,则用sockt.js和stomp.js
function connect() { var socket = new SockJS('/log/hello/hello'); stompClient = Stomp.over(socket); stompClient.connect({},function(frame) { setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/greetings',function(greeting) { showGreeting(JSON.parse(greeting.body).content); }); }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("disconnected"); } function sendName() { var name = document.getElementById('name').value; stompClient.send("/app/hello",{},JSON.stringify({ 'name' : name })); }
在浏览器中可以看到请求返回101状态码,意思就是切换协议
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
关于javax.websocket.Endpoint的实例源码和java websocketclient的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker的实例源码、java WebSocket的实现以及Spring WebSocket示例代码的相关信息,请在本站寻找。
本文标签: