本文将带您了解关于javax.websocket.server.PathParam的实例源码的新内容,同时我们还将为您解释javawebsocketclient的相关知识,另外,我们还将为您提供关于i
本文将带您了解关于javax.websocket.server.PathParam的实例源码的新内容,同时我们还将为您解释java websocketclient的相关知识,另外,我们还将为您提供关于io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码的实用信息。
本文目录一览:- javax.websocket.server.PathParam的实例源码(java websocketclient)
- io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码
- io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码
- io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码
- io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码
javax.websocket.server.PathParam的实例源码(java websocketclient)
@OnMessage public void onMessage(Session session,String message,@PathParam("id") Long id,@PathParam("nickname") String nickname) { LOGGER.info("Received message: " + message + " from " + nickname + " and channel n°" + id); JsonObject json = GsonSingleton.getInstance().fromJson(message,JsonObject.class); if (json != null) { String content = json.get(JSON_KEY_CONTENT).getAsstring(); Long channelId = json.get(JSON_KEY_CHANNEL_ID).getAsLong(); Long userId = json.get(JSON_KEY_USER_ID).getAsLong(); Message mess = new Message.Builder() .setContent(content) .setChannelId(channelId) .setNickname(nickname) .setUserId(userId) .build(); try (Connection c = DatabaseManager.getConnection()) { MessageDAO messageDAO = new MessageDAO(c); if (messageDAO.create(mess)) manager.broadcast(id,mess,From.Type.CLIENT); } catch (sqlException | InsertionException e) { e.printstacktrace(); } } }
/** * Close the connection and decrement the number of writers and send a * message to notify all others writers. * * @param session * peer session * @param adocId * unique id for this asciidoc file */ @OnClose public void closedConnection(Session session,@PathParam("projectId") String adocId) { if (session.getUserProperties().containsKey("writer")) { handleWriters(adocId,false,(String) session.getUserProperties() .get("writer")); } else { handleReaders(adocId,false); } peers.remove(session); logger.log(Level.INFO,"Connection closed for " + session.getId()); // send a message to all peers to inform that someone is disonnected sendNotificationMessage(createNotification(adocId),adocId); }
@Onopen public void onopen(Session session,@PathParam("uuid") String uuid) { UUID key = UUID.fromString(uuid); peers.put(key,session); JsonArrayBuilder builder = Json.createArrayBuilder(); for (StatusEventType statusEventType : StatusEventType.values()) { JsonObjectBuilder object = Json.createObjectBuilder(); builder.add(object.add(statusEventType.name(),statusEventType.getMessage()).build()); } RemoteEndpoint.Async asyncRemote = session.getAsyncRemote(); asyncRemote.sendText(builder.build().toString()); // Send pending messages List<String> messages = messageBuffer.remove(key); if (messages != null) { messages.forEach(asyncRemote::sendText); } }
@Onopen public void open(@PathParam("gametype") String gameID,Session session) throws IOException { type = GameType.getGameType(gameID); if(type == null) { session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION,"Invalid game type")); return; } Basic sender = session.getBasicRemote(); viewer = data -> { synchronized(session) { if(session.isopen()) try { sender.sendBinary(data); } catch (IOException e) {} } }; displayHandler.addGlobalViewer(viewer); }
@Onopen public void userConnectedCallback(@PathParam("user") String user,Session s) { if (USERS.contains(user)) { try { dupUserDetected = true; s.getBasicRemote().sendText("Username " + user + " has been taken. Retry with a different name"); s.close(); return; } catch (IOException ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE,null,ex); } } this.s = s; s.getUserProperties().put("user",user); this.user = user; USERS.add(user); welcomeNewJoinee(); announceNewJoinee(); }
@Onopen public void userConnectedCallback(@PathParam("user") String user,Session s) { if (USERS.contains(user)) { try { dupUserDetected = true; s.getBasicRemote().sendobject(new DuplicateUserNotification(user)); s.close(); return; } catch (Exception ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE,ex); } } this.s = s; SESSIONS.add(s); s.getUserProperties().put("user",user); this.user = user; USERS.add(user); welcomeNewJoinee(); announceNewJoinee(); }
@OnMessage public void onWebSocketText(final Session sess,final JSONRPC2Message msg,@PathParam(CCOWContextListener.PATH_NAME) final String applicationName) { if (msg instanceof JSONRPC2Request) { //All operations that are invokable on ContextManager that does not return void logger.debug("The message is a Request"); } else if (msg instanceof JSONRPC2Notification) { //All operations that are invokable on ContextManager that does return void logger.debug("The message is a Notification"); } else if (msg instanceof JSONRPC2Response) { //All operations that are invokable from ContextManager that does not return void and are initially called from ContextManager participant.onMessage((JSONRPC2Response) msg); logger.debug("The message is a Response"); } }
@OnMessage public void requestEventTracking(@PathParam("trackingPin") String trackingPin,Session session) { myLog.debug("requestEventTracking: " + trackingPin); try { if (session.isopen()) { SecqMeEventVO eventVO = eventManager.getEventByTrackingPin(trackingPin); FullEventInfoVO eventInfoVO = eventManager.getFullEventInfoOfContact(eventVO.getId()); session.getBasicRemote().sendText(eventInfoVO.toJSON().toString()); } } catch (IOException ex) { myLog.error("Tracking event web socket error: " + trackingPin,ex); try { session.close(); } catch (IOException ex1) { // Ignore } } }
/** * Open a socket connection to a client from the web server * * @param session The session that just opened */ @Onopen public void openSocket(@PathParam(RT_COmpuTE_ENDPOINT_ParaM) ConnectionType type,Session session) { session.setMaxIdleTimeout(0); String sessionId = session.getId(); if (type == ConnectionType.SUBSCRIBER) { LOG.info("Got a new subscriber connection request with ID {}. Saving session",sessionId); // cleanup sessions Set<Session> closedSessions = Sets.newHashSet(); for (Session existingSession : sessions) { if (!existingSession.isopen()) { closedSessions.add(existingSession); } } sessions.removeAll(closedSessions); sessions.add(session); LOG.info("Active sessions {}. Collecting {} sessions",sessions.size(),closedSessions.size()); } else { LOG.info("Got a new publisher connection request with ID {}",sessionId); } }
@Onopen public void onopen(Session session,@PathParam("username") String username) { try{ client.add(session); user.put(URLEncoder.encode(username,"UTF-8"),URLEncoder.encode(username,"UTF-8")); JSONObject jo = new JSONObject(); JSONArray ja = new JSONArray(); //获得在线用户列表 Set<String> key = user.keySet(); for (String u : key) { ja.add(u); } jo.put("onlineUser",ja); session.getBasicRemote().sendText(jo.toString()); }catch(Exception e){ //do nothing } }
@Onopen public void onopen(Session session,session); JsonArrayBuilder builder = Json.createArrayBuilder(); for (StatusMessage statusMessage : StatusMessage.values()) { JsonObjectBuilder object = Json.createObjectBuilder(); builder.add(object.add(statusMessage.name(),statusMessage.getMessage()).build()); } RemoteEndpoint.Async asyncRemote = session.getAsyncRemote(); asyncRemote.sendText(builder.build().toString()); // Send pending messages List<String> messages = messageBuffer.remove(key); if (messages != null) { messages.forEach(asyncRemote::sendText); } }
@OnMessage public void message(final Session session,BetMessage msg,@PathParam("match-id") String matchId) { logger.log(Level.INFO,"Received: Bet Match Winner - {0}",msg.getWinner()); //check if the user had already bet and save this bet boolean hasAlreadyBet = session.getUserProperties().containsKey("bet"); session.getUserProperties().put("bet",msg.getWinner()); //Send betMsg with bet count if (!nbBetsByMatch.containsKey(matchId)){ nbBetsByMatch.put(matchId,new AtomicInteger()); } if (!hasAlreadyBet){ nbBetsByMatch.get(matchId).incrementAndGet(); } sendBetMessages(null,matchId,false); }
private boolean validateOnopenMethod(Object webSocketEndpoint) throws WebSocketMethodParameterException,WebSocketEndpointMethodReturnTypeException { Endpointdispatcher dispatcher = new Endpointdispatcher(); Method method; if (dispatcher.getonopenMethod(webSocketEndpoint).isPresent()) { method = dispatcher.getonopenMethod(webSocketEndpoint).get(); } else { return true; } validateReturnType(method); for (Parameter parameter: method.getParameters()) { Class<?> paraType = parameter.getType(); if (paraType == String.class) { if (parameter.getAnnotation(PathParam.class) == null) { throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " + "string parameter without " + "@PathParam annotation."); } } else if (paraType != Session.class) { throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " + paraType); } } return true; }
private boolean validateOnCloseMethod(Object webSocketEndpoint) throws WebSocketMethodParameterException,WebSocketEndpointMethodReturnTypeException { Endpointdispatcher dispatcher = new Endpointdispatcher(); Method method; if (dispatcher.getonCloseMethod(webSocketEndpoint).isPresent()) { method = dispatcher.getonCloseMethod(webSocketEndpoint).get(); } else { return true; } validateReturnType(method); for (Parameter parameter: method.getParameters()) { Class<?> paraType = parameter.getType(); if (paraType == String.class) { if (parameter.getAnnotation(PathParam.class) == null) { throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " + "string parameter without " + "@PathParam annotation."); } } else if (paraType != CloseReason.class && paraType != Session.class) { throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " + paraType); } } return true; }
/** * Extract OnMessage method for String from the endpoint if exists. * * @param webSocketEndpoint Endpoint to extract method. * @return method optional to handle String messages. */ public Optional<Method> getonStringMessageMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getmethods(); Method returnMethod = null; for (Method method : methods) { if (method.isAnnotationPresent(OnMessage.class)) { Parameter[] parameters = method.getParameters(); for (Parameter parameter: parameters) { if (!parameter.isAnnotationPresent(PathParam.class) && parameter.getType() == String.class) { returnMethod = method; } } } } return Optional.ofNullable(returnMethod); }
private void handleError(Throwable throwable,PatternPathRouter.RoutableDestination<Object> routableEndpoint,Session session) { Object webSocketEndpoint = routableEndpoint.getDestination(); Map<String,String> paramValues = routableEndpoint.getGroupNameValues(); Optional<Method> methodoptional = new Endpointdispatcher().getonErrorMethod(webSocketEndpoint); methodoptional.ifPresent(method -> { List<Object> parameterList = new LinkedList<>(); Arrays.stream(method.getParameters()).forEach(parameter -> { if (parameter.getType() == Throwable.class) { parameterList.add(throwable); } else if (parameter.getType() == Session.class) { parameterList.add(session); } else if (parameter.getType() == String.class) { PathParam pathParam = parameter.getAnnotation(PathParam.class); if (pathParam != null) { parameterList.add(paramValues.get(pathParam.value())); } } else { parameterList.add(null); } }); executeMethod(method,webSocketEndpoint,parameterList,session); }); }
/** * Message is received from the JS client * * @param message * @param session * @throws IOException */ @OnMessage public void onMessage(@PathParam("userId") String userId,RoutedMessage message,Session session) throws IOException { Log.log(Level.FInesT,this,"C -> M R : {0}",message); try { if (message.getFlowTarget() == FlowTarget.ready) { // wait to process the ready message until we've validated the JWT (see onopen) mediatorCheck.await(); clientMediator.ready(message); goodToGo = true; // eventually all threads will see that we're happy } else if (goodToGo || mediatorCheck.getCount() == 0) { // we will eventually see the goodToGo check,which will bypass having to look @ the latch clientMediator.handleMessage(message); } else { Log.log(Level.FInesT,session,"no session,dropping message from client {0}: {1}",userId,message); return; } } catch (Exception e) { Log.log(Level.WARNING,"Uncaught exception handling room-bound message",e); } }
@OnMessage public void handleSubscribeMessage(Session session,String msg,@PathParam("topic") String topic) { { if (session.isopen()) { if(topic!=null && !topic.trim().isEmpty()){ System.out.println("We have a clinet for: " + topic); PublicationsManager.getInstance().onSubscribe(session,topic.trim()); } else{ try { session.getBasicRemote().sendText("Please use a valid topic name to subscribe"); } catch (IOException e) { //Ignore topic was null anyways cannot do much about this client } } } } }
@OnMessage public void onMessage(String message,Session session,@PathParam("user") String user) { switch (session.getNegotiatedSubprotocol()) { case "text": getTextMessageHandler().onMessage(message,user); break; case "json": try { getJsonMessageHandler().onMessage(JacksonSupport.objectMapper.readTree(message),user); } catch (Exception e) { logger.error("process message:[{}] due to error:[{}]",message,ExceptionUtils.getStackTrace(e)); } break; case "echo": session.getAsyncRemote().sendText(String.format("reply from server:[%s]",message)); break; } }
@OnMessage public void message(final Session session,false); }
/** * Callback when receiving opened connection from client side * * @param session the client {@link Session} * @param config the associated {@link EndpointConfig} to the new connection * @param executionId the execution identifier from the {@link ServerEndpoint} path */ @Onopen public void openConnection(Session session,EndpointConfig config,@PathParam("execution-id") long executionId) { if (LOG.isDebugEnabled()) { LOG.debug("Session " + session.getId() + " opened connection to execution " + executionId); } mainLock.lock(); try { sessions.put(session.getId(),session); Set<String> registeredSessions = executions.get(executionId); if (registeredSessions == null) { registeredSessions = new HashSet<>(); } registeredSessions.add(session.getId()); executions.put(executionId,registeredSessions); } finally { mainLock.unlock(); } }
/** * Callback when receiving closed connection from client side * * @param session the client {@link Session} * @param executionId the execution identifier from the {@link ServerEndpoint} path */ @OnClose public void closedConnection(Session session,@PathParam("execution-id") long executionId) { if (LOG.isDebugEnabled()) { LOG.debug("Session " + session.getId() + " closed connection to execution " + executionId); } mainLock.lock(); try { sessions.remove(session.getId()); Set<String> registeredSessions = executions.get(executionId); if (registeredSessions != null) { registeredSessions.remove(session.getId()); } } finally { mainLock.unlock(); } }
@Onopen public void onopen(Session session,@PathParam("nickname") String nickname) throws IOException { LOGGER.info("onopen " + id + ": " + session.toString()); manager.add(session,id); Message message = new Message.Builder() .setContent("Welcom " + nickname + "!") .setNickname(nickname) .build(); manager.broadcast(id,From.Type.SERVER); }
@OnClose public void onClose(Session session,CloseReason reason,@PathParam("nickname") String nickname) throws IOException { //prepare the endpoint for closing. LOGGER.info("onClose: " + session.toString()); manager.remove(session,id); Message json = new Message.Builder() .setContent("Bye bye " + nickname + "...") .setNickname(nickname) .build(); manager.broadcast(id,json,From.Type.SERVER); }
@OnMessage public void onMessage(@PathParam("ws") String ws,@PathParam("lang") String lang,Session session) { if ( message.length() == 0 ) return; // This is just ping! IdleTimeHolder.getInstance().registerUserActivity(); LOG.info("LSP: onMessage is invoked: \n" + message); LOG.info(String.format("LSP: get Head Process for wsKey %s lang %s session %s",ws,lang,session.getId())); LSPProcess lspProc = procManager.getProcess(LSPProcessManager.processKey(ws,lang)); lspProc.enqueueCall(message); }
@OnClose public void onClose(@PathParam("ws") String ws,CloseReason reason ) { Map<String,List<String>> reqParam = session.getRequestParameterMap(); if ( reqParam != null && reqParam.containsKey("local") ) { return; } LOG.info("LSP: OnClose is invoked"); LSPProcess process = procManager.getProcess(LSPProcessManager.processKey(ws,lang)); if (process != null) { registerWSSyncListener(LSPProcessManager.processKey(process.getProjPath(),lang),"/" + ws + "/" + lang,false); procManager.cleanProcess(ws,session.getId()); } }
@Onopen public void onopen(final Session session,@PathParam("id") String id) { session.setMaxIdleTimeout(0); SimulationModel model = simstore.get(UUID.fromString(id)); Simulation sim = model.getSimulation(); SimulationWrapper wrapper = (SimulationWrapper) model.getWrapper(sim); Runnable sendConfigurationUpdate = () -> { if(sim.getController().isPaused() || !sim.getController().isActive()) { return; } sim.getController().doActionNow(() -> { Boundary[] boundaries = new Boundary[sim.getBoxCount()]; for (int i = 0; i < sim.getBoxCount(); i++) { boundaries[i] = sim.getBox(i).getBoundary(); } ConfigurationUpdate update = new ConfigurationUpdate( wrapper.getAllCoordinates(),boundaries ); session.getAsyncRemote().sendobject(update); }); }; ScheduledFuture<?> task = executor.scheduleWithFixedDelay(sendConfigurationUpdate,33,TimeUnit.MILLISECONDS); session.getUserProperties().put("task",task); }
@Onopen public void onopen(final Session session,@PathParam("simId") String simId,@PathParam("dataId") String dataId) { session.setMaxIdleTimeout(0); session.getUserProperties().put("mapper",mapper); SimulationModel model = simstore.get(UUID.fromString(simId)); Simulation sim = model.getSimulation(); DataStreamStore.DataPlumbing dataPlumbing = dataStore.get(UUID.fromString(dataId)); DataDump dump = dataPlumbing.getDump(); final DataAndInfo dataAndInfo = new DataAndInfo(); Runnable sendData = () -> { if(sim.getController().isPaused() || !sim.getController().isActive()) { return; } sim.getController().doActionNow(() -> { IData data = dump.getData(); dataAndInfo.setData(dump.getData()); dataAndInfo.setDataInfo(dump.getDataInfo()); if(data != null) { session.getAsyncRemote().sendobject(dataAndInfo); } }); }; ScheduledFuture<?> task = executor.scheduleWithFixedDelay(sendData,333,TimeUnit.MILLISECONDS); session.getUserProperties().put("task",task); // add on construction // model.getSimulation().getIntegrator().getEventManager().addListener(dataPlumbing.getPump()); }
@Onopen public void open(Session session,@PathParam(value = "user")String user) { Session session1 = sessionMap.get(user); if (null != session1) { try { session1.close(); } catch (IOException e) { e.printstacktrace(); } } sessionMap.put(user,session); log.info("*** WebSocket opened from sessionId " + session.getId()); }
@Onopen public void opened(@PathParam("user") String user,EndpointConfig config) throws IOException{ System.out.println("opened() Current thread "+ Thread.currentThread().getName()); this.httpSession = (HttpSession) config.getUserProperties().get(user); System.out.println("User joined "+ user + " with http session id "+ httpSession.getId()); String response = "User " + user + " | WebSocket session ID "+ session.getId() +" | HTTP session ID " + httpSession.getId(); System.out.println(response); session.getBasicRemote().sendText(response); }
/** * Heartbeat endpoint. * Registers that the client is still there and updates configuration * if changed. * * @param clientId The client id * @param applicationConfig The updated configuration */ @OnMessage public void onMessage(@PathParam("clientId") String clientId,String applicationConfig) { LOGGER.config(() -> "Client: " + clientId + ",status: " + applicationConfig); if (applicationConfig != null && !applicationConfig.isEmpty()) { clients.register(fromJSON(applicationConfig)); } else { clients.deRegister(clientId); } }
@OnMessage public void onMessage(String message,@PathParam("username") String username) { try{ JSONObject jo = new JSONObject(); JSONObject inner = new JSONObject(); inner.put("message",message); inner.put("username",username); jo.put("onlineMessage",inner); for (Session c : client) { c.getBasicRemote().sendText(jo.toString()); } }catch(Exception e){ //do nothing } }
@OnClose public void onClose(Session session,@PathParam("username") String username) { try{ client.remove(session); user.remove(URLEncoder.encode(username,"UTF-8")); session.close(); }catch(Exception e){ //do nothing } }
@Onopen public void onopen(Session session,@PathParam("sensor") String sensor) { if ("ALL".equals(sensor)) { sensor = null; } send(sensor,session); sessions.add(sensor,session); }
@Onopen public void openConnection(Session session,@PathParam("projectId") String adocId) { logger.log(Level.INFO,"Session ID : " + session.getId() + " - Connection opened for doc : " + adocId); session.getUserProperties().put(adocId,true); peers.add(session); // send a message to all peers to inform that someone is connected handleReaders(adocId,true); if (!writersByAdoc.containsKey(adocId)) { writersByAdoc.put(adocId,new HashSet<String>()); } sendNotificationMessage(createNotification(adocId),adocId); }
/** * Heartbeat endpoint. * Registers that the client is still there and updates configuration * if changed. * * @param clientId The client id * @param applicationConfig The updated configuration */ @OnMessage public void onMessage(@PathParam("clientId") String clientId,status: " + applicationConfig); if (applicationConfig != null && !applicationConfig.isEmpty()) { clients.register(fromJSON(applicationConfig)); } else { clients.deRegister(clientId); } }
@Onopen public void openConnection(Session session,"Session ID : " + session.getId() +" - Connection opened for match : " + matchId); session.getUserProperties().put(matchId,true); peers.add(session); //Send live result for this match try { send(new MatchMessage(ejbService.getMatchFromCache(new Long(matchId))),matchId); } catch (Exception e){ logger.severe("Error to get match from cache." + e.getCause()); } }
@OnClose public void closedConnection(Session session,@PathParam("match-id") String matchId) { if (session.getUserProperties().containsKey("bet")){ /* Remove bet */ nbBetsByMatch.get(matchId).decrementAndGet(); sendBetMessages(null,false); } /* Remove this connection from the queue */ peers.remove(session); logger.log(Level.INFO,"Connection closed."); }
@Onopen public void open(Session conn,@PathParam("projectID") String projectId) throws AppException { try { this.session = conn; this.sender = (String) config.getUserProperties().get("user"); this.project = getProject(projectId); authenticateUser(conn,this.project,this.sender); if (this.userRole == null) { LOG.log(Level.INFO,"User not authorized for Zeppelin Access: {0}",this.sender); return; } if (project.getPaymentType().equals(PaymentType.PREPAID)) { YarnProjectsQuota projectQuota = yarnProjectsQuotaFacade.findByProjectName(project.getName()); if (projectQuota == null || projectQuota.getQuotaRemaining() < 0) { session.close(new CloseReason(CloseReason.CloseCodes.norMAL_CLOSURE,"This project is out of credits.")); return; } } this.impl = notebookServerImplFactory.getNotebookServerImps(project.getName(),conn); if (impl.getConf() == null) { impl.removeConnectedSockets(conn,notebookServerImplFactory); LOG.log(Level.INFO,"Could not create Zeppelin config for user: {0},project: {1}",new Object[]{this.sender,project.getName()}); return; } addUserConnection(this.hdfsUsername,conn); addUserConnection(project.getProjectGenericUser(),conn); this.session.getUserProperties().put("projectID",this.project.getId()); String httpHeader = (String) config.getUserProperties().get(WatcherSecurityKey.HTTP_HEADER); this.session.getUserProperties().put(WatcherSecurityKey.HTTP_HEADER,httpHeader); impl.unicast(new Message(OP.CREATED_SOCKET),conn); } catch (IOException | RepositoryException | TaskRunnerException ex) { throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),ex.getMessage()); } }
/** * Invoked when a client connects to the server * @param session * @param clientType - type of the client */ @Onopen public void onopen(Session session,EndpointConfig endConfig,@PathParam("clientType") String clientType) { logger.log(Level.INFO,"Connection has been established."); consumer = context.createConsumer(topic); consumer.setMessageListener(null); producer = context.createProducer(); producer.send(topic,"Hello World!"); }
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()); }
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; }
关于javax.websocket.server.PathParam的实例源码和java websocketclient的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.PingWebSocketFrame的实例源码、io.netty.handler.codec.http.websocketx.PongWebSocketFrame的实例源码的相关知识,请在本站寻找。
本文标签: