org.tio.core.ChannelContext Java Examples
The following examples show how to use
org.tio.core.ChannelContext.
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: BsIds.java From t-io with Apache License 2.0 | 6 votes |
/** * * @param channelContext * @author tanyaowu */ public void unbind(ChannelContext channelContext) { TioConfig tioConfig = channelContext.tioConfig; if (tioConfig.isShortConnection) { return; } String bsId = channelContext.getBsId(); if (StrUtil.isBlank(bsId)) { return; } try { map.remove(bsId); channelContext.setBsId(null); } catch (Exception e) { log.error(e.toString(), e); } }
Example #2
Source File: WsServerAioHandler.java From t-io with Apache License 2.0 | 6 votes |
@Override public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) { WsResponse wsResponse = (WsResponse) packet; // 握手包 if (wsResponse.isHandShake()) { WsSessionContext imSessionContext = (WsSessionContext) channelContext.get(); HttpResponse handshakeResponse = imSessionContext.getHandshakeResponse(); try { return HttpResponseEncoder.encode(handshakeResponse, tioConfig, channelContext); } catch (UnsupportedEncodingException e) { log.error(e.toString(), e); return null; } } ByteBuffer byteBuffer = WsServerEncoder.encode(wsResponse, tioConfig, channelContext); return byteBuffer; }
Example #3
Source File: WsClientAioListener.java From t-io with Apache License 2.0 | 6 votes |
@Override public void onBeforeClose( ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception { WsClient client = (WsClient) channelContext.getAttribute(WebSocketImpl.clientIntoCtxAttribute); if (throwable instanceof SSLHandshakeException && client.uri.getScheme().equals("wss")) { log.warn("wss但没有正确的CA证书,更为ws重试"); ReflectKit.setField(client.uri, "scheme", "ws"); if (client.uri.getPort() == 443) ReflectKit.setField(client.uri, "port", 80); client.construct(); client.connect(); return; } client.ws.clear(1011, remark); channelContext.setAttribute(WebSocketImpl.clientIntoCtxAttribute, null); }
Example #4
Source File: FetchBlockResponseHandler.java From md_blockchain with Apache License 2.0 | 6 votes |
@Override public Object handler(BlockPacket packet, RpcBlockBody rpcBlockBody, ChannelContext channelContext) { logger.info("收到来自于<" + rpcBlockBody.getAppId() + ">的回复,Block为:" + Json.toJson(rpcBlockBody)); Block block = rpcBlockBody.getBlock(); //如果为null,说明对方也没有该Block if (block == null) { logger.info("对方也没有该Block"); } else { //此处校验传过来的block的合法性,如果合法,则更新到本地,作为next区块 CheckerManager checkerManager = ApplicationContextProvider.getBean(CheckerManager.class); RpcCheckBlockBody rpcCheckBlockBody = checkerManager.check(block); //校验通过,则存入本地DB,保存新区块 if (rpcCheckBlockBody.getCode() == 0) { ApplicationContextProvider.publishEvent(new AddBlockEvent(block)); //继续请求下一块 BlockPacket blockPacket = NextBlockPacketBuilder.build(); ApplicationContextProvider.getBean(PacketSender.class).sendGroup(blockPacket); } } return null; }
Example #5
Source File: WsServerAioHandler.java From t-io with Apache License 2.0 | 6 votes |
private WsResponse processRetObj(Object obj, String methodName, ChannelContext channelContext) throws Exception { WsResponse wsResponse = null; if (obj == null) { return null; } else { if (obj instanceof String) { String str = (String) obj; wsResponse = WsResponse.fromText(str, wsServerConfig.getCharset()); return wsResponse; } else if (obj instanceof byte[]) { wsResponse = WsResponse.fromBytes((byte[]) obj); return wsResponse; } else if (obj instanceof WsResponse) { return (WsResponse) obj; } else if (obj instanceof ByteBuffer) { byte[] bs = ((ByteBuffer) obj).array(); wsResponse = WsResponse.fromBytes(bs); return wsResponse; } else { log.error("{} {}.{}()方法,只允许返回byte[]、ByteBuffer、WsResponse或null,但是程序返回了{}", channelContext, this.getClass().getName(), methodName, obj.getClass().getName()); return null; } } }
Example #6
Source File: AbstractAioHandler.java From md_blockchain with Apache License 2.0 | 5 votes |
/** * 编码:把业务消息包编码为可以发送的ByteBuffer * 消息头:type + bodyLength * 消息体:byte[] */ @Override public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) { BlockPacket showcasePacket = (BlockPacket) packet; byte[] body = showcasePacket.getBody(); int bodyLen = 0; if (body != null) { bodyLen = body.length; } //总长度是消息头的长度+消息体的长度 int allLen = BlockPacket.HEADER_LENGTH + bodyLen; ByteBuffer buffer = ByteBuffer.allocate(allLen); buffer.order(groupContext.getByteOrder()); //写入消息类型 buffer.put(showcasePacket.getType()); //写入消息体长度 buffer.putInt(bodyLen); //写入消息体 if (body != null) { buffer.put(body); } return buffer; }
Example #7
Source File: Ids.java From t-io with Apache License 2.0 | 5 votes |
/** * Find. * * @param id the id * @return the channel context */ public ChannelContext find(TioConfig tioConfig, String id) { if (tioConfig.isShortConnection) { return null; } if (StrUtil.isBlank(id)) { return null; } return map.get(id); }
Example #8
Source File: WsServerAioListener.java From t-io with Apache License 2.0 | 5 votes |
@SuppressWarnings("deprecation") @Override public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception { WsSessionContext wsSessionContext = new WsSessionContext(); channelContext.set(wsSessionContext); return; }
Example #9
Source File: HttpClientAioHandler.java From t-io with Apache License 2.0 | 5 votes |
@Override public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) { ClientHttpRequest request = (ClientHttpRequest) packet; ByteBuffer byteBuffer; try { byteBuffer = HttpRequestEncoder.encode(request, tioConfig, channelContext); return byteBuffer; } catch (UnsupportedEncodingException e) { log.error(e.toString(), e); return null; } }
Example #10
Source File: WsClientAioHander.java From t-io with Apache License 2.0 | 5 votes |
@Override public void handler(Packet packet, ChannelContext ctx) throws Exception { if (packet instanceof WsPacket) { WsPacket wsPacket = (WsPacket) packet; if (!wsPacket.isWsEof()) { return; } } Subject<Packet> packetPublisher = (Subject<Packet>) ctx.getAttribute(WebSocketImpl.packetPublisherKey); packetPublisher.onNext(packet); }
Example #11
Source File: SSLFacade.java From t-io with Apache License 2.0 | 5 votes |
public SSLFacade(ChannelContext channelContext, SSLContext context, boolean client, boolean clientAuthRequired, ITaskHandler taskHandler) { this.channelContext = channelContext; //Currently there is no support for SSL session reuse, // so no need to take a peerHost or port from the host application final String who = client ? "client" : "server"; SSLEngine engine = makeSSLEngine(context, client, clientAuthRequired); Buffers buffers = new Buffers(engine.getSession(), channelContext); _worker = new Worker(who, engine, buffers, channelContext); _handshaker = new Handshaker(client, _worker, taskHandler, channelContext); _clientMode = client; }
Example #12
Source File: MaintainUtils.java From t-io with Apache License 2.0 | 5 votes |
public static void deleteTempDir(ChannelContext channelContext) { if (channelContext.hasTempDir) { try { File dirFile = tempDir(channelContext, false); FileUtil.del(dirFile); } catch (Exception e) { log.error(e.toString(), e); } } }
Example #13
Source File: ClientNodes.java From t-io with Apache License 2.0 | 5 votes |
/** * * @param key * @return * @author tanyaowu */ public ChannelContext find(String key) { Lock lock = mapWithLock.readLock(); lock.lock(); try { Map<String, ChannelContext> m = mapWithLock.getObj(); return m.get(key); } catch (Throwable e) { throw e; } finally { lock.unlock(); } }
Example #14
Source File: Users.java From t-io with Apache License 2.0 | 5 votes |
/** * 解除channelContext绑定的userid * * @param channelContext the channel context */ public void unbind(ChannelContext channelContext) { if (channelContext.tioConfig.isShortConnection) { return; } String userid = channelContext.userid; if (StrUtil.isBlank(userid)) { log.debug("{}, {}, 并没有绑定用户", channelContext.tioConfig.getName(), channelContext.toString()); return; } try { SetWithLock<ChannelContext> setWithLock = mapWithLock.get(userid); if (setWithLock == null) { log.warn("{}, {}, userid:{}, 没有找到对应的SetWithLock", channelContext.tioConfig.getName(), channelContext.toString(), userid); return; } setWithLock.remove(channelContext); if (setWithLock.size() == 0) { mapWithLock.remove(userid); } channelContext.setUserid(null); } catch (Throwable e) { log.error(e.toString(), e); } }
Example #15
Source File: TioRpcServerEndpoint.java From nutzcloud with Apache License 2.0 | 5 votes |
@Override public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException { if (readableLength < HEADER_LENGHT) return null; // 读取消息体的长度 int bodyLength = buffer.getInt(); // 数据不正确,则抛出AioDecodeException异常 if (bodyLength < 2) { throw new AioDecodeException("bodyLength [" + bodyLength + "] is not right, remote:" + channelContext.getClientNode()); } // 计算本次需要的数据长度 int neededLength = HEADER_LENGHT + bodyLength; // 收到的数据是否足够组包 int isDataEnough = readableLength - neededLength; // 不够消息体长度(剩下的buffe组不了消息体) if (isDataEnough < 0) { return null; } else // 组包成功 { LiteRpcPacket rpcPacket = new LiteRpcPacket(); // 版本信息占一个字节 byte version = buffer.get(); if (version != 1) {} // 操作类型占一个字节 rpcPacket.opType = buffer.get(); if (rpcPacket.opType == OP_PING) { // 心跳包没有剩余信息,清除多余的body,返回null if (bodyLength > 2) buffer.clear(); return null; } byte[] dst = new byte[bodyLength - 2]; buffer.get(dst); // log.debug(Lang.fixedHexString(dst)); rpcPacket.setBody(dst); return rpcPacket; } }
Example #16
Source File: BaseAioHandler.java From blockchain with Apache License 2.0 | 5 votes |
/** * 编码:把业务消息包编码为可以发送的ByteBuffer * 总的消息结构:消息头 + 消息类别 + 消息体 * 消息头结构: 4个字节,存储消息体的长度 * 消息类别: 1 个字节, 存储类别,S => 字符串, B => 区块, T => 交易 * 消息体结构: 对象的json串的byte[] */ public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) { MessagePacket messagePacket = (MessagePacket) packet; byte[] body = messagePacket.getBody(); int bodyLen = 0; if (body != null) { bodyLen = body.length; } //bytebuffer的总长度是 = 消息头的长度 + 消息体的长度 int allLen = MessagePacket.HEADER_LENGTH + bodyLen; //创建一个新的bytebuffer ByteBuffer buffer = ByteBuffer.allocate(allLen); //设置字节序 buffer.order(groupContext.getByteOrder()); //写入消息类型 buffer.put(messagePacket.getType()); //写入消息头----消息头的内容就是消息体的长度 buffer.putInt(bodyLen); //写入消息体 if (body != null) { buffer.put(body); } return buffer; }
Example #17
Source File: ClientNodes.java From t-io with Apache License 2.0 | 5 votes |
/** * 添加映射 * @param channelContext * @author tanyaowu */ public void put(ChannelContext channelContext) { if (channelContext.tioConfig.isShortConnection) { return; } try { String key = getKey(channelContext); mapWithLock.put(key, channelContext); } catch (Exception e) { log.error(e.toString(), e); } }
Example #18
Source File: BlockClientAioListener.java From md_blockchain with Apache License 2.0 | 5 votes |
@Override public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception { if (isConnected) { logger.info("连接成功:server地址为-" + channelContext.getServerNode()); Aio.bindGroup(channelContext, GROUP_NAME); } else { logger.info("连接失败:server地址为-" + channelContext.getServerNode()); } }
Example #19
Source File: TioUtils.java From t-io with Apache License 2.0 | 5 votes |
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 #20
Source File: TotalBlockInfoResponseHandler.java From md_blockchain with Apache License 2.0 | 5 votes |
@Override public Object handler(BlockPacket packet, RpcBlockBody rpcBlockBody, ChannelContext channelContext) throws Exception { logger.info("收到<请求生成Block的回应>消息", Json.toJson(rpcBlockBody)); //TODO check合法性 //TODO response return null; }
Example #21
Source File: HttpResponseDecoder.java From t-io with Apache License 2.0 | 5 votes |
/** * 先粗暴地简单解析一下 * @param httpResponse * @param bodyBytes * @param channelContext * @throws AioDecodeException * @author tanyaowu */ private static void parseBody(ClientHttpResponse httpResponse, byte[] bodyBytes, ChannelContext channelContext) throws AioDecodeException { if (bodyBytes != null) { try { httpResponse.setBodyString(new String(bodyBytes, "utf-8")); } catch (UnsupportedEncodingException e) { log.error(e.toString(), e); } } }
Example #22
Source File: ClientNodes.java From t-io with Apache License 2.0 | 5 votes |
/** * * @param channelContext * @return * @author tanyaowu */ public static String getKey(ChannelContext channelContext) { Node clientNode = channelContext.getClientNode(); if (clientNode == null) { throw new RuntimeException("client node is null"); } String key = getKey(clientNode.getIp(), clientNode.getPort()); return key; }
Example #23
Source File: PbftVoteHandler.java From md_blockchain with Apache License 2.0 | 5 votes |
@Override public Object handler(BlockPacket packet, VoteBody voteBody, ChannelContext channelContext) { VoteMsg voteMsg = voteBody.getVoteMsg(); logger.info("收到来自于<" + voteMsg.getAppId() + "><投票>消息,投票信息为[" + voteMsg + "]"); ApplicationContextProvider.getBean(MsgQueueManager.class).pushMsg(voteMsg); return null; }
Example #24
Source File: BsIds.java From t-io with Apache License 2.0 | 5 votes |
/** * * @param tioConfig * @param bsId * @return * @author tanyaowu */ public ChannelContext find(TioConfig tioConfig, String bsId) { if (tioConfig.isShortConnection) { return null; } if (StrUtil.isBlank(bsId)) { return null; } return map.get(bsId); }
Example #25
Source File: BlockServerAioListener.java From md_blockchain with Apache License 2.0 | 5 votes |
@Override public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) { log.info("onAfterConnected channelContext:{}, isConnected:{}, isReconnect:{}", channelContext, isConnected, isReconnect); //连接后,需要把连接会话对象设置给channelContext //channelContext.setAttribute(new ShowcaseSessionContext()); }
Example #26
Source File: HttpServerAioListener.java From t-io with Apache License 2.0 | 5 votes |
@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 #27
Source File: BlockClientAioHandler.java From md_blockchain with Apache License 2.0 | 5 votes |
/** * server端返回的响应会先进到该方法,将消息全丢到Disruptor中 */ @Override public void handler(Packet packet, ChannelContext channelContext) { BlockPacket blockPacket = (BlockPacket) packet; //使用Disruptor来publish消息。所有收到的消息都进入Disruptor,同BlockServerAioHandler ApplicationContextProvider.getBean(MessageProducer.class).publish(new BaseEvent(blockPacket, channelContext)); }
Example #28
Source File: MaintainUtils.java From t-io with Apache License 2.0 | 4 votes |
public static File tempWriteFile(ChannelContext channelContext) { File tempDir = tempDir(channelContext, true); File tempReceivedFile = new File(tempDir, "write"); return tempReceivedFile; }
Example #29
Source File: WsServerAioListener.java From t-io with Apache License 2.0 | 4 votes |
@Override public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception { }
Example #30
Source File: HttpResponseDecoder.java From t-io with Apache License 2.0 | 4 votes |
/** * @param buffer * @param limit * @param position * @param readableLength * @param channelContext * @return * @throws AioDecodeException * @author tanyaowu */ public static HttpResponse decode( ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException { Map<String, String> headers = new HashMap<>(); int contentLength = 0; byte[] bodyBytes = null; StringBuilder headerSb = null; // new StringBuilder(512); ResponseLine firstLine = null; boolean appendRequestHeaderString = true; if (appendRequestHeaderString) { headerSb = new StringBuilder(512); } // request line connect firstLine = parseResponseLine(buffer, channelContext); if (firstLine == null) { return null; } // request line end // request header connect boolean headerCompleted = parseHeaderLine(buffer, headers, 0); if (!headerCompleted) { return null; } String contentLengthStr = headers.get(HttpConst.ResponseHeaderKey.Content_Length); if (StrUtil.isBlank(contentLengthStr)) { contentLength = 0; } else { contentLength = Integer.parseInt(contentLengthStr); } int headerLength = (buffer.position() - position); int allNeedLength = headerLength + contentLength; // 这个packet所需要的字节长度(含头部和体部) if (readableLength < allNeedLength) { channelContext.setPacketNeededLength(allNeedLength); return null; } // request header end // ----------------------------------------------- request body connect HttpResponse httpResponse = new HttpResponse(); // httpResponse.setChannelContext(channelContext); // httpResponse.setHttpConfig((HttpConfig) // channelContext.tioConfig.getAttribute(TioConfigKey.HTTP_SERVER_CONFIG)); if (appendRequestHeaderString) { httpResponse.setHeaderString(headerSb.toString()); } else { httpResponse.setHeaderString(""); } // httpResponse.setResponseLine(firstLine); httpResponse.setStatus(HttpResponseStatus.getHttpStatus(firstLine.status)); httpResponse.addHeaders( headers.entrySet().stream() .collect( Collectors.toMap( entry -> HeaderName.from(entry.getKey()), entry -> HeaderValue.from(entry.getValue())))); // httpResponse.setContentLength(contentLength); String connection = headers.get(HttpConst.ResponseHeaderKey.Connection); if (connection != null) { // httpResponse.setConnection(connection.toLowerCase()); } if (contentLength == 0) { // if (StrUtil.isNotBlank(firstLine.getQuery())) { // decodeParams(httpResponse.getParams(), firstLine.getQuery(), httpResponse.getCharset(), // channelContext); // } } else { bodyBytes = new byte[contentLength]; buffer.get(bodyBytes); httpResponse.setBody(bodyBytes); // 解析消息体 parseBody(httpResponse, bodyBytes, channelContext); } // ----------------------------------------------- request body end return httpResponse; }