io.netty.handler.codec.http.websocketx.TextWebSocketFrame Java Examples

The following examples show how to use io.netty.handler.codec.http.websocketx.TextWebSocketFrame. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IpcdClientDevice.java    From arcusipcd with Apache License 2.0 6 votes vote down vote up
private void sendMessage(String json) {
	if (!isConnected()) {
		throw new IllegalStateException("Cannot send message because not connected");
	}
	
	int buffersize = deviceModel.getBuffersize();
	
	int startPos = 0;
   	TextWebSocketFrame respFrame = new TextWebSocketFrame(
   			startPos + buffersize >= json.length(),
   			0,
   			json.substring(startPos, Math.min(json.length(), (startPos + buffersize)))
   		);
   	channel.writeAndFlush(respFrame);
   	startPos += buffersize;
   	while (startPos < json.length()) {
   		ContinuationWebSocketFrame contFrame = new ContinuationWebSocketFrame(
   					startPos + buffersize >= json.length(),
   					0,
   					json.substring(startPos, Math.min(json.length(), (startPos + buffersize)))
   				);
   		startPos += buffersize;
   		channel.writeAndFlush(contFrame);
   	}
}
 
Example #2
Source File: TextWebSocketFrameHandler.java    From netty-learning with MIT License 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE){
        //删除之前 HttpRequestHandle
        ctx.pipeline().remove(HttpRequestHandle.class) ;

        //通知所有已经连接的客户端 有新的连接来了
        group.writeAndFlush(new TextWebSocketFrame("新的客户端=" + ctx.channel() + "连接上来了")) ;

        //将当前的 channel 也就是 websocket channel 加入到 channelGroup 当中
        group.add(ctx.channel()) ;
    }else {
        //交给下一个 channelHandler 处理
        super.userEventTriggered(ctx, evt);
    }

}
 
Example #3
Source File: WebSocketService.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
public void handle(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (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);
}
 
Example #4
Source File: NettyWebSocketSessionSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected WebSocketFrame toFrame(WebSocketMessage message) {
	ByteBuf byteBuf = NettyDataBufferFactory.toByteBuf(message.getPayload());
	if (WebSocketMessage.Type.TEXT.equals(message.getType())) {
		return new TextWebSocketFrame(byteBuf);
	}
	else if (WebSocketMessage.Type.BINARY.equals(message.getType())) {
		return new BinaryWebSocketFrame(byteBuf);
	}
	else if (WebSocketMessage.Type.PING.equals(message.getType())) {
		return new PingWebSocketFrame(byteBuf);
	}
	else if (WebSocketMessage.Type.PONG.equals(message.getType())) {
		return new PongWebSocketFrame(byteBuf);
	}
	else {
		throw new IllegalArgumentException("Unexpected message type: " + message.getType());
	}
}
 
Example #5
Source File: Client.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void fire(final String message) {
   Channel channel = this.channelRef.get();
   if (channel != null) {
      channel.writeAndFlush(new TextWebSocketFrame(message));
   }
   else if(websocket != null) {
      // If the channel is null, then the client is probably in a state where it is 
      // connecting but the websocket isn't up yet.
   	// TODO: How many times do we reschedule before giving up?
      eventLoopGroup.schedule(new Runnable() {
         @Override
         public void run() {
            fire(message);
         }
      }, 1, TimeUnit.SECONDS);
   }
   else {
      throw new IllegalStateException("Client is closed, can't send message");
   }
}
 
Example #6
Source File: AutobahnServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
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()));
    }
}
 
Example #7
Source File: ChatServerHandler.java    From SpringMVC-Project with MIT License 6 votes vote down vote up
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
    String userName = null;
    for (Map.Entry<ChannelHandlerContext, String> entry : userChannelMap.entrySet()) {
        if (entry.getKey() == ctx) {
            userName = entry.getValue();
            userChannelMap.remove(ctx);
            break;
        }
    }

    if (userName != null) {
        for (ChannelHandlerContext context : userChannelMap.keySet()) {
            context.writeAndFlush(new TextWebSocketFrame("用户[" + userName + "] 离开聊天室"));
        }
    }
}
 
Example #8
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnMessage(Channel channel, WebSocketFrame frame) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
    }
    if (methodMapping.getOnMessage() != null) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        Object implement = channel.attr(POJO_KEY).get();
        try {
            methodMapping.getOnMessage().invoke(implement, methodMapping.getOnMessageArgs(channel, textFrame));
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example #9
Source File: HttpWsServer.java    From zbus-server with MIT License 6 votes vote down vote up
private byte[] 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());
	}
	
	logger.warn("Message format error: " + frame); 
	return null;
}
 
Example #10
Source File: WebSocketUpgradeHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
  if (frame instanceof CloseWebSocketFrame) {
    handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    // Pass on to the rest of the channel
    ctx.fireChannelRead(frame);
  } else if (frame instanceof PingWebSocketFrame) {
    ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()));
  } else if (frame instanceof ContinuationWebSocketFrame) {
    ctx.write(frame);
  } else if (frame instanceof PongWebSocketFrame) {
    frame.release();
  } else if (frame instanceof BinaryWebSocketFrame || frame instanceof TextWebSocketFrame) {
    // Allow the rest of the pipeline to deal with this.
    ctx.fireChannelRead(frame);
  } else {
    throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
      .getName()));
  }
}
 
Example #11
Source File: UserInfoManager.java    From netty-chat with Apache License 2.0 6 votes vote down vote up
/**
 * 广播系统消息
 */
public static void broadCastInfo(int code, Object mess) {
    try {
        rwLock.readLock().lock();
        Set<Channel> keySet = userInfos.keySet();
        for (Channel ch : keySet) {
            UserInfo userInfo = userInfos.get(ch);
            if (userInfo == null || !userInfo.isAuth()) {
                continue;
            }
            ch.writeAndFlush(new TextWebSocketFrame(ChatProto.buildSystProto(code, mess)));
        }
    } finally {
        rwLock.readLock().unlock();
    }
}
 
Example #12
Source File: WebSocketIT.java    From timely with Apache License 2.0 6 votes vote down vote up
@Test
public void testWSMetrics() throws Exception {
    try {
        MetricsRequest request = new MetricsRequest();
        ch.writeAndFlush(new TextWebSocketFrame(JsonUtil.getObjectMapper().writeValueAsString(request)));

        // Confirm receipt of all data sent to this point
        List<String> response = handler.getResponses();
        while (response.size() == 0 && handler.isConnected()) {
            LOG.info("Waiting for web socket response");
            sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
            response = handler.getResponses();
        }
        Assert.assertEquals(1, response.size());
        Assert.assertEquals("{\"metrics\":[]}", response.get(0));
    } finally {
        ch.close().sync();
        s.shutdown();
        group.shutdownGracefully();
    }
}
 
Example #13
Source File: ChatHandler.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest,处理参数
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap = getUrlParams(uri);
            //如果url包含参数,需要处理
            if (uri.contains("?")) {
                String newUri = uri.substring(0, uri.indexOf("?"));
                request.setUri(newUri);
            }
            Object obj = paramMap.get("token");
            if (null == obj || "undefined".equals(obj)) {
                ctx.channel().close();
                return;
            }
            ChannelManager.putChannel(ChannelManager.channelLongText(ctx), ctx.channel());
        } else if (msg instanceof TextWebSocketFrame) {
            //正常的TEXT消息类型
//            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
        }
        super.channelRead(ctx, msg);
    }
 
Example #14
Source File: CustomOfflineInfoHelper.java    From netty-chat with Apache License 2.0 6 votes vote down vote up
public void pullThread() {
    new Thread(() -> {
        while (true) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            UserInfoManager.rwLock.readLock().lock();
            for (Channel channel : channels) {
                UserInfo userInfo = userInfos.get(channel);
                List<String> strings = CustomOfflineInfoHelper.infoMap.get(userInfo.getId());
                for (String string : strings) {
                    channel.writeAndFlush(new TextWebSocketFrame(ChatProto.buildMessProto(userInfo.getId(), userInfo.getUsername(), string)));
                }
                strings.clear();
            }
            UserInfoManager.rwLock.readLock().unlock();
        }
    }).start();
}
 
Example #15
Source File: HttpChannelImpl.java    From InChat with Apache License 2.0 6 votes vote down vote up
@Override
public void sendFromServer(Channel channel, SendServerVO serverVO) {
    if (serverVO.getToken() == "") {
        notFindUri(channel);
    }
    Channel userChannel = WebSocketCacheMap.getByToken(serverVO.getToken());
    if (userChannel == null) {
        log.info(LogConstant.HTTPCHANNELSERVICEIMPL_NOTFINDLOGIN);
        notFindToken(channel);
    }
    String value = fromServerService.findByCode(Integer.parseInt(serverVO.getValue()));
    SendServer sendServer = new SendServer(value);
    try {
        userChannel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(sendServer)));
        sendServer(channel, UndefinedInChatConstant.SEND_SUCCESS);
    } catch (Exception e) {
        log.info(LogConstant.HTTPCHANNELSERVICEIMPL_SEND_EXCEPTION);
    }
}
 
Example #16
Source File: WebSocketRequestDecoderTest.java    From timely with Apache License 2.0 6 votes vote down vote up
@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.getSecurity());
// @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());
}
 
Example #17
Source File: Ipcd10WebSocketServerHandler.java    From arcusipcd with Apache License 2.0 6 votes vote down vote up
private void handleMessageCompleted(ChannelHandlerContext ctx, String json) {
	// parse the message
    if (logger.isDebugEnabled()) {
        //logger.debug(String.format("%s received %s", ctx.channel(), json));
    	comlog.info("Device=>Server " + ctx.channel().remoteAddress() + "=>" + ctx.channel().localAddress() + " : " + json);
    }
    
    IpcdSerializer ser = new IpcdSerializer();
    ClientMessage msg = ser.parseClientMessage(new StringReader(json));
    
    // set device on the session if the session is not yet initialized
    if (!session.isInitialized()) {
    	session.setDevice(msg.getDevice());
    	SessionRegistry.putSesion(session);
    }
    
    ServerMessage response = handleClientMessage(msg);
    
    if (response != null) {
    	ctx.channel().write(new TextWebSocketFrame(ser.toJson(response)));
    }
}
 
Example #18
Source File: WsGremlinTextRequestDecoder.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final TextWebSocketFrame frame, final List<Object> objects) throws Exception {
    try {
        // the default serializer must be a MessageTextSerializer instance to be compatible with this decoder
        final MessageTextSerializer serializer = (MessageTextSerializer) select("application/json", ServerSerializers.DEFAULT_TEXT_SERIALIZER);

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

        objects.add(serializer.deserializeRequest(frame.text()));
    } catch (SerializationException se) {
        objects.add(RequestMessage.INVALID);
    }
}
 
Example #19
Source File: NettyWebSocketSessionSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected WebSocketFrame toFrame(WebSocketMessage message) {
	ByteBuf byteBuf = NettyDataBufferFactory.toByteBuf(message.getPayload());
	if (WebSocketMessage.Type.TEXT.equals(message.getType())) {
		return new TextWebSocketFrame(byteBuf);
	}
	else if (WebSocketMessage.Type.BINARY.equals(message.getType())) {
		return new BinaryWebSocketFrame(byteBuf);
	}
	else if (WebSocketMessage.Type.PING.equals(message.getType())) {
		return new PingWebSocketFrame(byteBuf);
	}
	else if (WebSocketMessage.Type.PONG.equals(message.getType())) {
		return new PongWebSocketFrame(byteBuf);
	}
	else {
		throw new IllegalArgumentException("Unexpected message type: " + message.getType());
	}
}
 
Example #20
Source File: PerFrameDeflateEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
    return (msg instanceof TextWebSocketFrame ||
            msg instanceof BinaryWebSocketFrame ||
            msg instanceof ContinuationWebSocketFrame) &&
                ((WebSocketFrame) msg).content().readableBytes() > 0 &&
                (((WebSocketFrame) msg).rsv() & WebSocketExtension.RSV1) == 0;
}
 
Example #21
Source File: WebSocketServerHandlerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRead0HandleTextFrame() throws Exception {
   ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
   Object msg = new TextWebSocketFrame();

   spy.channelRead0(ctx, msg); //test

   verify(spy).channelRead0(ctx, msg);
   verify(ctx).fireChannelRead(any(ByteBuf.class));
   verifyNoMoreInteractions(spy, ctx);
}
 
Example #22
Source File: WebSocketIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@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());
        }
    } 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());
    }
}
 
Example #23
Source File: TunnelSocketFrameHandler.java    From arthas with Apache License 2.0 5 votes vote down vote up
private void agentRegister(ChannelHandlerContext ctx, String requestUri) throws URISyntaxException {
    // generate a random agent id
    String id = RandomStringUtils.random(20, true, true).toUpperCase();

    QueryStringDecoder queryDecoder = new QueryStringDecoder(requestUri);
    List<String> idList = queryDecoder.parameters().get("id");
    if (idList != null && !idList.isEmpty()) {
        id = idList.get(0);
    }

    final String finalId = id;

    URI responseUri = new URI("response", null, "/", "method=agentRegister" + "&id=" + id, null);

    AgentInfo info = new AgentInfo();
    SocketAddress remoteAddress = ctx.channel().remoteAddress();
    if (remoteAddress instanceof InetSocketAddress) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
        info.setHost(inetSocketAddress.getHostString());
        info.setPort(inetSocketAddress.getPort());
    }
    info.setChannelHandlerContext(ctx);

    tunnelServer.addAgent(id, info);
    ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            tunnelServer.removeAgent(finalId);
        }

    });

    ctx.channel().writeAndFlush(new TextWebSocketFrame(responseUri.toString()));
}
 
Example #24
Source File: WebSocketRemoteServerFrameHandler.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    if (frame instanceof TextWebSocketFrame) {
        // Echos the same text
        String text = ((TextWebSocketFrame) frame).text();
        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);
    }
}
 
Example #25
Source File: WsServerHandler.java    From openzaly with Apache License 2.0 5 votes vote down vote up
private void doWSRequest(ChannelHandlerContext ctx, WebSocketFrame wsFrame) {
	InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
	String clientIp = socketAddress.getAddress().getHostAddress();
	ChannelSession channelSession = ctx.channel().attr(ChannelConst.CHANNELSESSION).get();

	Command command = new Command();
	command.setSiteUserId(channelSession.getUserId());
	command.setClientIp(clientIp);
	command.setStartTime(System.currentTimeMillis());

	if (wsFrame instanceof TextWebSocketFrame) {
		TextWebSocketFrame textWsFrame = (TextWebSocketFrame) wsFrame;
		String webText = textWsFrame.text();
		try {
			command.setParams(webText.getBytes(CharsetCoding.UTF_8));
		} catch (UnsupportedEncodingException e) {
			logger.error("web message text=" + webText + " Charset code error");
		}
		TextWebSocketFrame resFrame = new TextWebSocketFrame(textWsFrame.text());
		ctx.channel().writeAndFlush(resFrame);

		executor.execute("WS-ACTION", command);
	} else if (wsFrame instanceof PingWebSocketFrame) {
		// ping/pong
		ctx.channel().writeAndFlush(new PongWebSocketFrame(wsFrame.content().retain()));
		logger.info("ws client siteUserId={} ping to server", command.getSiteUserId());
	} else if (wsFrame instanceof CloseWebSocketFrame) {
		// close channel
		wsHandshaker.close(ctx.channel(), (CloseWebSocketFrame) wsFrame.retain());
		WebChannelManager.delChannelSession(command.getSiteUserId());
	}
}
 
Example #26
Source File: MessageCrypto.java    From jeesupport with MIT License 5 votes vote down vote up
/**
 * S2C
 * 将对象序列化为byte[]
 *
 * @param _obj 序列化对象
 * @return 序列化后的byte[]值
 */
public static < T > Object serializer( ByteBuf _buf, T _obj, boolean _ws ){
	boolean proxy = CommonConfig.getBoolean( "jees.jsts.message.proxy", true );
	String type = CommonConfig.getString( "jees.jsts.message.type", MSG_TYPE_PROTO );

	byte[] data = null;
	if( type.equalsIgnoreCase( MSG_TYPE_JSON ) ){
		if( _ws ) {
			return new TextWebSocketFrame( _obj.toString() );
		}else{
			if( proxy ) {
				data = serializer( _obj );
			}else{
				data = _obj.toString().getBytes();
			}
		}
	}else{
		if( _ws ) {
			return new TextWebSocketFrame( _obj.toString() );
		}else {
			data = serializer( _obj );
		}
	}

	if( data != null ){
		int dataLength = data.length;
		if( CommonConfig.getBoolean( "jees.jsts.socket.bom", false ) ){
			dataLength = DataUtil.warpHL( dataLength );
		}
		_buf.writeInt( dataLength );
		_buf.writeBytes( data );
	}

	return _buf;
}
 
Example #27
Source File: TestController.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/sendWebsocket")
public JSONResult sendWebsocket() {
    Map<String, Channel> channelHashMap = UserChannelCurrentMap.getAllChannel();
    if (MapUtils.isNotEmpty(channelHashMap)) {
        channelHashMap.forEach((s, channel) -> channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(JSONResult.ok(s + "我是服务器端发送消息/n")))));
        return JSONResult.ok(channelHashMap);
    }
    return JSONResult.errorException("没有通道");
}
 
Example #28
Source File: PerMessageDeflateEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
    return ((msg instanceof TextWebSocketFrame ||
            msg instanceof BinaryWebSocketFrame) &&
               (((WebSocketFrame) msg).rsv() & WebSocketExtension.RSV1) == 0) ||
           (msg instanceof ContinuationWebSocketFrame && compressing);
}
 
Example #29
Source File: WsServerHandler.java    From openzaly with Apache License 2.0 5 votes vote down vote up
private void doWSRequest(ChannelHandlerContext ctx, WebSocketFrame wsFrame) {
	InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
	String clientIp = socketAddress.getAddress().getHostAddress();
	ChannelSession channelSession = ctx.channel().attr(ChannelConst.CHANNELSESSION).get();

	Command command = new Command();
	command.setSiteUserId(channelSession.getUserId());
	command.setClientIp(clientIp);
	command.setStartTime(System.currentTimeMillis());

	if (wsFrame instanceof TextWebSocketFrame) {
		TextWebSocketFrame textWsFrame = (TextWebSocketFrame) wsFrame;
		String webText = textWsFrame.text();
		try {
			command.setParams(webText.getBytes(CharsetCoding.UTF_8));
		} catch (UnsupportedEncodingException e) {
			logger.error("web message text=" + webText + " Charset code error");
		}
		TextWebSocketFrame resFrame = new TextWebSocketFrame(textWsFrame.text());
		ctx.channel().writeAndFlush(resFrame);

		executor.execute("WS-ACTION", command);
	} else if (wsFrame instanceof PingWebSocketFrame) {
		// ping/pong
		ctx.channel().writeAndFlush(new PongWebSocketFrame(wsFrame.content().retain()));
		logger.info("ws client siteUserId={} ping to server", command.getSiteUserId());
	} else if (wsFrame instanceof CloseWebSocketFrame) {
		// close channel
		wsHandshaker.close(ctx.channel(), (CloseWebSocketFrame) wsFrame.retain());
		WebChannelManager.delChannelSession(command.getSiteUserId());
	}
}
 
Example #30
Source File: AppServer.java    From reactor-guice with Apache License 2.0 5 votes vote down vote up
private static void testWebsocketClient() throws IOException {
    Properties properties = new Properties();
    // properties.load(new FileInputStream("D:\\project\\reactor-guice\\application.properties"));
    properties.load(new FileInputStream("/Users/develop/Project/reactor-guice/application.properties"));

    int port = Integer.valueOf(properties.getProperty("server.port", "8081"));

    FluxProcessor<String, String> client = ReplayProcessor.<String>create().serialize();

    Flux.interval(Duration.ofMillis(1000))
        .map(Object::toString)
        .subscribe(client::onNext);

    HttpClient.create()
        // .port(port)
        // .wiretap(true)
        .websocket()
        .uri("ws://127.0.0.1:8083/kreactor/ws")
        .handle((in, out) ->
            out.withConnection(conn -> {
                in.aggregateFrames().receiveFrames().map(frames -> {
                    if (frames instanceof TextWebSocketFrame) {
                        System.out.println("Receive text message " + ((TextWebSocketFrame) frames).text());
                    }
                    else if (frames instanceof BinaryWebSocketFrame) {
                        System.out.println("Receive binary message " + frames.content());
                    }
                    else {
                        System.out.println("Receive normal message " + frames.content());
                    }
                    return Mono.empty();
                })
                    .subscribe();
            })
                // .options(NettyPipeline.SendOptions::flushOnEach)
                .sendString(client)
        )
        .blockLast();
}