org.tio.core.Tio Java Examples

The following examples show how to use org.tio.core.Tio. 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: IpBlacklist.java    From t-io with Apache License 2.0 6 votes vote down vote up
public boolean add(String ip) {
	//先添加到黑名单列表
	cache.put(ip, SystemTimer.currTime);

	if (serverTioConfig != null) {
		//删除相关连接
		Tio.remove(serverTioConfig, ip, "ip[" + ip + "]被加入了黑名单, " + serverTioConfig.getName());
	} else {
		TioConfig.ALL_SERVER_GROUPCONTEXTS.stream().forEach(new Consumer<ServerTioConfig>() {
			@Override
			public void accept(ServerTioConfig tioConfig) {
				Tio.remove(tioConfig, ip, "ip[" + ip + "]被加入了黑名单, " + tioConfig.getName());

			}
		});
	}

	return true;
}
 
Example #2
Source File: SendRunnable.java    From t-io with Apache License 2.0 6 votes vote down vote up
public boolean sendPacket(Packet packet) {
	ByteBuffer byteBuffer = getByteBuffer(packet);
	if (isSsl) {
		if (!packet.isSslEncrypted()) {
			SslVo sslVo = new SslVo(byteBuffer, packet);
			try {
				channelContext.sslFacadeContext.getSslFacade().encrypt(sslVo);
				byteBuffer = sslVo.getByteBuffer();
			} catch (SSLException e) {
				log.error(channelContext.toString() + ", 进行SSL加密时发生了异常", e);
				Tio.close(channelContext, "进行SSL加密时发生了异常", CloseCode.SSL_ENCRYPTION_ERROR);
				return false;
			}
		}
	}

	sendByteBuffer(byteBuffer, packet);
	return true;
}
 
Example #3
Source File: TioRpcServerEndpoint.java    From nutzcloud with Apache License 2.0 6 votes vote down vote up
protected void sendRpcResp(ChannelContext channelContext, RpcResp resp, RpcSerializer serializer, LiteRpcPacket rpcPacket) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        if (resp.err != null) {
            out.write(2);
            serializer.write(resp.err, out);
        } else if (resp.returnValue == null) {
            out.write(0);
        } else {
            out.write(1);
            serializer.write(resp.returnValue, out);
        }
    }
    catch (Exception e) {
        if (debug && log.isDebugEnabled())
            log.debug(e.getMessage(), e);
        throw e;
    }
    rpcPacket.body = out.toByteArray();
    // log.debug(Lang.fixedHexString(rpcPacket.body));
    rpcPacket.opType = OP_RPC_RESP;
    Tio.send(channelContext, rpcPacket);
}
 
Example #4
Source File: PushController.java    From tio-starters with MIT License 5 votes vote down vote up
@GetMapping("/msg")
public void pushMessage(String msg){
    if (StrUtil.isEmpty(msg)){
        msg = "hello tio websockedddddt";
    }
    Tio.sendToAll(bootstrap.getServerGroupContext(), WsResponse.fromText(msg,"utf-8"));
}
 
Example #5
Source File: HttpClientStarter.java    From t-io with Apache License 2.0 5 votes vote down vote up
public static void gsOsc() throws Exception {
	boolean useSsl = false;
	String serverip = "www.baidu.com";
	int serverport = 80;
	String path = "/";
	//		String requestPath = "/json";
	String queryString = "";

	HttpClientStarter httpClientStarter;
	if (useSsl) {
		httpClientStarter = org.tio.http.client.HttpClientStarter.httpsClientStarter;
	} else {
		httpClientStarter = org.tio.http.client.HttpClientStarter.httpClientStarter;
	}

	Node serverNode = new Node(serverip, serverport);
	clientChannelContextArray = new ClientChannelContext[clientCount];
	for (int i = 0; i < clientCount; i++) {
		clientChannelContextArray[i] = httpClientStarter.tioClient.connect(serverNode);
	}

	requestCount = 10000; //每个客户端的请求数
	clientCount = 100; //客户端个数
	totalRequestCount = requestCount * clientCount; //总请求数
	stepCount = totalRequestCount / 10;
	startTime = System.currentTimeMillis();
	stageStartTime = System.currentTimeMillis();

	//received
	receivedCount = new AtomicLong();
	receivedStageCount = new AtomicLong();

	System.out.println("start time:" + startTime + "(" + DateUtil.formatDateTime(new Date(startTime)) + ")");
	ClientHttpRequest clientHttpRequest = ClientHttpRequest.get(path, queryString);
	for (int i = 0; i < clientCount; i++) {
		for (int j = 0; j < requestCount; j++) {
			Tio.send(clientChannelContextArray[i], clientHttpRequest);
		}
	}
}
 
Example #6
Source File: HttpServerAioListener.java    From t-io with Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) {
	//		if ((channelContext.sslFacadeContext == null || channelContext.sslFacadeContext.isHandshakeCompleted())/** && packet instanceof HttpResponse*/
	//		) {}

	HttpResponse httpResponse = (HttpResponse) packet;
	HttpRequest request = httpResponse.getHttpRequest();
	//		String connection = request.getConnection();

	if (request != null) {
		if (request.httpConfig.compatible1_0) {
			switch (request.requestLine.version) {
			case HttpConst.HttpVersion.V1_0:
				if (!HttpConst.RequestHeaderValue.Connection.keep_alive.equals(request.getConnection())) {
					Tio.remove(channelContext, "http 请求头Connection!=keep-alive:" + request.getRequestLine());
				}
				break;

			default:
				if (HttpConst.RequestHeaderValue.Connection.close.equals(request.getConnection())) {
					Tio.remove(channelContext, "http 请求头Connection=close:" + request.getRequestLine());
				}
				break;
			}
		} else {
			if (HttpConst.RequestHeaderValue.Connection.close.equals(request.getConnection())) {
				Tio.remove(channelContext, "http 请求头Connection=close:" + request.getRequestLine());
			}
		}
	}
}
 
Example #7
Source File: FlashPolicyServerStarter.java    From t-io with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {

	while (true) {
		try {
			Thread.sleep(10 * 1000);
		} catch (InterruptedException e1) {
			log.error(e1.toString(), e1);
		}

		SetWithLock<ChannelContext> setWithLock = serverTioConfig.connections;
		Set<ChannelContext> set = null;
		ReadLock readLock = setWithLock.readLock();
		readLock.lock();
		try {
			long now = SystemTimer.currTime;
			set = setWithLock.getObj();
			for (ChannelContext channelContext : set) {
				long interval = (now - channelContext.stat.timeFirstConnected);
				if (interval > 5000) {
					Tio.remove(channelContext, "已经连上来有" + interval + "ms了,该断开啦");
				}
			}
		} catch (java.lang.Throwable e) {
			log.error("", e);
		} finally {
			readLock.unlock();
		}
	}
}
 
Example #8
Source File: TioUtils.java    From t-io with Apache License 2.0 5 votes vote down vote up
public static boolean checkBeforeIO(ChannelContext channelContext) {
	if (channelContext.isWaitingClose) {
		return false;
	}

	Boolean isopen = null;
	if (channelContext.asynchronousSocketChannel != null) {
		isopen = channelContext.asynchronousSocketChannel.isOpen();

		if (channelContext.isClosed || channelContext.isRemoved) {
			if (isopen) {
				try {
					Tio.close(channelContext,
					        "asynchronousSocketChannel is open, but channelContext isClosed: " + channelContext.isClosed + ", isRemoved: " + channelContext.isRemoved, CloseCode.CHANNEL_NOT_OPEN);
				} catch (Throwable e) {
					log.error(e.toString(), e);
				}
			}
			log.info("{}, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, isopen, channelContext.isClosed, channelContext.isRemoved);
			return false;
		}
	} else {
		log.error("{}, 请检查此异常, asynchronousSocketChannel is null, isClosed:{}, isRemoved:{}, {} ", channelContext, channelContext.isClosed, channelContext.isRemoved,
		        ThreadUtils.stackTrace());
		return false;
	}

	if (!isopen) {
		log.info("{}, 可能对方关闭了连接, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, isopen, channelContext.isClosed, channelContext.isRemoved);
		Tio.close(channelContext, "asynchronousSocketChannel is not open, 可能对方关闭了连接", CloseCode.CHANNEL_NOT_OPEN);
		return false;
	}
	return true;
}
 
Example #9
Source File: SpringBootWsMsgHandler.java    From tio-starters with MIT License 4 votes vote down vote up
/**
 * binaryType=text
 * */
@Override
public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {
    Tio.sendToAll(channelContext.getGroupContext(), WsResponse.fromText("服务端收到了消息:"+s,"utf-8"));
    return null;
}
 
Example #10
Source File: WebSocketImpl.java    From t-io with Apache License 2.0 4 votes vote down vote up
private void handshake() {
  readyState = WebSocket.CONNECTING;

  ClientChannelContext ctx = wsClient.getClientChannelContext();
  WsSessionContext session = (WsSessionContext) ctx.get();

  session.setHandshaked(false);

  String path = wsClient.uri.getPath();
  if (StrUtil.isBlank(path)) {
    path = "/";
  }
  ClientHttpRequest httpRequest =
      new ClientHttpRequest(Method.GET, path, wsClient.uri.getRawQuery());
  Map<String, String> headers = new HashMap<>();
  if (additionalHttpHeaders != null) headers.putAll(additionalHttpHeaders);
  headers.put("Host", wsClient.uri.getHost() + ":" + wsClient.uri.getPort());
  headers.put("Upgrade", "websocket");
  headers.put("Connection", "Upgrade");
  headers.put("Sec-WebSocket-Key", getSecWebsocketKey());
  headers.put("Sec-WebSocket-Version", "13");
  httpRequest.setHeaders(headers);

  session.setHandshakeRequest(httpRequest);

  ObjKit.Box<Disposable> disposableBox = ObjKit.box(null);

  disposableBox.value =
      publisher
          .filter(packet -> !session.isHandshaked())
          .subscribe(
              packet -> {
                if (packet instanceof HttpResponse) {
                  HttpResponse resp = (HttpResponse) packet;

                  if (resp.getStatus() == HttpResponseStatus.C101) {
                    HeaderValue upgrade = resp.getHeader(HeaderName.Upgrade);
                    if (upgrade == null || !upgrade.value.toLowerCase().equals("websocket")) {
                      close(1002, "no upgrade or upgrade invalid");
                      return;
                    }
                    HeaderValue connection = resp.getHeader(HeaderName.Connection);
                    if (connection == null || !connection.value.toLowerCase().equals("upgrade")) {
                      close(1002, "no connection or connection invalid");
                      return;
                    }
                    HeaderValue secWebsocketAccept =
                        resp.getHeader(HeaderName.Sec_WebSocket_Accept);
                    if (secWebsocketAccept == null
                        || !verifySecWebsocketAccept(secWebsocketAccept.value)) {
                      close(1002, "no Sec_WebSocket_Accept or Sec_WebSocket_Accept invalid");
                      return;
                    }
                    // TODO: Sec-WebSocket-Extensions, Sec-WebSocket-Protocol

                    readyState = WebSocket.OPEN;
                    session.setHandshaked(true);
                    onOpen();
                  } else {
                    // TODO: support other http code
                    close(1002, "not support http code: " + resp.getStatus().status);
                    return;
                  }

                  disposableBox.value.dispose();
                }
              });

  Tio.send(ctx, httpRequest);
}
 
Example #11
Source File: WebSocketImpl.java    From t-io with Apache License 2.0 4 votes vote down vote up
private void bindInitStreamObserver() {
  sendWsPacketStream
      .buffer(sendNotifier) // Is it need back pressure control?
      .subscribe(
          packets -> packets.forEach(this::sendImmediately),
          this::onThrows,
          sendNotifier::onComplete);
  getMessageStream()
      .subscribe(
          p -> {
            Consumer<MessageEvent> onMessage = wsClient.config.getOnMessage();
            if (onMessage != null) {
              onMessage.accept(new MessageEvent(p));
            }
          },
          this::onThrows);
  getWsPacketStream()
      .filter(p -> p.getWsOpcode().equals(Opcode.CLOSE))
      .subscribe(
          packet -> {
            if (readyState == WebSocket.CLOSED) return;
            byte[] body = packet.getBody();
            short code = 1000;
            String reason = "";
            if (body != null && body.length >= 2) {
              ByteBuffer bodyBuf = ByteBuffer.wrap(body);
              code = bodyBuf.getShort();
              byte[] reasonBytes = new byte[body.length - 2];
              bodyBuf.get(reasonBytes, 0, reasonBytes.length);
              reason = new String(reasonBytes, "UTF-8");
            }
            if (readyState == WebSocket.CLOSING) {
              clear(code, reason);
            } else {
              readyState = WebSocket.CLOSING;
              packet.setBody(ByteBuffer.allocate(2).putShort(code).array());
              Tio.send(ctx, packet);
              close(code, reason);
            }
          });
  getWsPacketStream()
      .filter(p -> p.getWsOpcode().equals(Opcode.PING))
      .subscribe(
          packet -> {
            WsPacket pong = new WsPacket();
            pong.setWsOpcode(Opcode.PONG);
            pong.setWsEof(true);
            Tio.send(ctx, pong);
          });
}
 
Example #12
Source File: HttpClientStarter.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * 开始测试
 * @throws Exception
 * @author tanyaowu
 */
public static void startTest(String serverip, int serverport, String path, int clientCount, int requestCount) throws Exception {
	boolean useSsl = false;
	String queryString = "";

	HttpClientStarter httpClientStarter;
	if (useSsl) {
		httpClientStarter = httpsClientStarter;
	} else {
		httpClientStarter = org.tio.http.client.HttpClientStarter.httpClientStarter;
	}

	HttpClientStarter.clientCount = clientCount; //客户端个数
	HttpClientStarter.requestCount = requestCount; //每个客户端的请求数
	HttpClientStarter.requestPath = path;

	HttpClientStarter.totalRequestCount = HttpClientStarter.requestCount * HttpClientStarter.clientCount; //总请求数
	HttpClientStarter.stepCount = HttpClientStarter.totalRequestCount / 10;

	Node serverNode = new Node(serverip, serverport);
	clientChannelContextArray = new ClientChannelContext[clientCount];
	for (int i = 0; i < clientCount; i++) {
		clientChannelContextArray[i] = httpClientStarter.tioClient.connect(serverNode);
	}

	startTime = System.currentTimeMillis();
	stageStartTime = System.currentTimeMillis();

	//received
	receivedCount = new AtomicLong();
	receivedStageCount = new AtomicLong();

	receivedBytes = new AtomicLong();
	receivedStageBytes = new AtomicLong();

	System.out.println("start time:" + startTime + "(" + DateUtil.formatDateTime(new Date(startTime)) + ")");
	ClientHttpRequest clientHttpRequest = ClientHttpRequest.get(requestPath, queryString);
	for (int i = 0; i < clientCount; i++) {
		for (int j = 0; j < requestCount; j++) {
			clientHttpRequest.addHeader(HttpConst.RequestHeaderKey.Host, clientChannelContextArray[i].getServerNode().getIp());
			Tio.send(clientChannelContextArray[i], clientHttpRequest);
		}
	}
}
 
Example #13
Source File: HttpRequest.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * 关闭连接
 * @param remark
 */
public void close(String remark) {
	closed = true;
	Tio.remove(channelContext, remark);
}
 
Example #14
Source File: FlashPolicyServerAioHandler.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * 处理消息
 */
@Override
public void handler(Packet packet, ChannelContext channelContext) throws Exception {
	Tio.send(channelContext, FlashPolicyPacket.RESPONSE);
	//		Tio.close(channelContext, "消息发送完毕");
}
 
Example #15
Source File: TioClusterMessageListener.java    From t-io with Apache License 2.0 4 votes vote down vote up
public void onMessage(CharSequence channel, TioClusterVo tioClusterVo) {
	log.info("收到topic:{}, count:{}, tioClusterVo:{}", channel, RECEIVED_TOPIC_COUNT.incrementAndGet(), Json.toJson(tioClusterVo));
	String clientid = tioClusterVo.getClientId();
	if (StrUtil.isBlank(clientid)) {
		log.error("clientid is null");
		return;
	}
	if (Objects.equals(TioClusterVo.CLIENTID, clientid)) {
		log.info("自己发布的消息,忽略掉,{}", clientid);
		return;
	}

	Packet packet = tioClusterVo.getPacket();
	if (packet == null) {
		log.error("packet is null");
		return;
	}
	packet.setFromCluster(true);

	//发送给所有
	boolean isToAll = tioClusterVo.isToAll();
	if (isToAll) {
		Tio.sendToAll(tioConfig, packet);
	}

	//发送给指定组
	String group = tioClusterVo.getGroup();
	if (StrUtil.isNotBlank(group)) {
		Tio.sendToGroup(tioConfig, group, packet);
	}

	//发送给指定用户
	String userid = tioClusterVo.getUserid();
	if (StrUtil.isNotBlank(userid)) {
		Tio.sendToUser(tioConfig, userid, packet);
	}

	//发送给指定token
	String token = tioClusterVo.getToken();
	if (StrUtil.isNotBlank(token)) {
		Tio.sendToToken(tioConfig, token, packet);
	}

	//发送给指定ip
	String ip = tioClusterVo.getIp();
	if (StrUtil.isNotBlank(ip)) {
		Tio.sendToIp(tioConfig, ip, packet);
	}

	//发送给指定channelId
	String channelId = tioClusterVo.getChannelId();
	if (StrUtil.isNotBlank(channelId)) {
		Tio.sendToId(tioConfig, channelId, packet);
	}

	//发送给指定bsId
	String bsId = tioClusterVo.getBsId();
	if (StrUtil.isNotBlank(bsId)) {
		Tio.sendToBsId(tioConfig, bsId, packet);
	}
}
 
Example #16
Source File: SslSessionClosedListener.java    From t-io with Apache License 2.0 4 votes vote down vote up
@Override
public void onSessionClosed() {
	//		log.info("{} onSessionClosed", channelContext);
	Tio.close(channelContext, "SSL SessionClosed", CloseCode.SSL_SESSION_CLOSED);
}