/** * 发送消息字符串 * * @param msg */ public void sendStringMsg(String msg) { ByteBuf message = Unpooled.buffer(msg.getBytes().length); message.writeBytes(msg.getBytes()); ChannelFuture future = channel.writeAndFlush(message); future.addListener((ChannelFutureListener) channelFuture -> LOGGER.info("客户端手动发消息成功={}", msg)); }
/** * 向服务器注册 */ private void loginCIMServer() { CIMRequestProto.CIMReqProtocol login = CIMRequestProto.CIMReqProtocol.newBuilder() .setRequestId(userId) .setReqMsg(userName) .setType(Constants.CommandType.LOGIN) .build(); ChannelFuture future = channel.writeAndFlush(login); future.addListener((ChannelFutureListener) channelFuture -> LOGGER.info("注册成功={}", login.toString())); }
/** * 发送 Google Protocol 编解码字符串 * * @param googleProtocolVO */ public void sendGoogleProtocolMsg(GoogleProtocolVO googleProtocolVO) { CIMRequestProto.CIMReqProtocol protocol = CIMRequestProto.CIMReqProtocol.newBuilder() .setRequestId(googleProtocolVO.getRequestId()) .setReqMsg(googleProtocolVO.getMsg()) .setType(Constants.CommandType.MSG) .build(); ChannelFuture future = channel.writeAndFlush(protocol); future.addListener((ChannelFutureListener) channelFuture -> LOGGER.info("客户端手动发送 Google Protocol 成功={}", googleProtocolVO.toString())); }
@Override protected void write(Object data, final Deferred<Void, Promise<Void>> onComplete, final boolean flush) { ChannelFuture writeFuture = (flush ? channel.writeAndFlush(data) : channel.write(data)); writeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { boolean success = future.isSuccess(); if(!success) { Throwable t = future.cause(); eventsReactor.notify(t, Event.wrap(t)); if(null != onComplete) { onComplete.accept(t); } } else if(null != onComplete) { onComplete.accept((Void)null); } } }); }
public void testWriteBeforeConnect(Bootstrap cb) throws Throwable { TestHandler h = new TestHandler(); SocketChannel ch = null; try { ch = (SocketChannel) cb.handler(h).connect(newSocketAddress()).channel(); ch.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 1 })); } finally { if (ch != null) { ch.close(); } } }
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf payload) throws Exception { LOG.trace("Got reply from echo server" + payload); System.out.println("Got reply from echo server" + payload); Channel ch = ctx.channel(); int sessionId = ch.attr(SESSION_ID).get(); int port = ch.attr(PORT).get(); UscData reply = null; ByteBuf subPayload = null; int length = payload.readableBytes(); int index = 0; int realLength = 0; while (length > 0) { realLength = (length > MAX_PAYLOAD_SIZE) ? MAX_PAYLOAD_SIZE : length; subPayload = payload.copy(index, realLength); index += realLength; length -= realLength; reply = new UscData(port, sessionId, subPayload); LOG.trace("Send to plugin " + reply); System.out.println("Send to plugin " + reply); plugin.writeAndFlush(reply); } } }
private void writeByteBuffer() { ByteBuf byteBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(command.dataOffset); byteBuffer.clear(); byteBuffer.writeBytes(command.dataBuffer, 0, command.dataOffset); ChannelFuture cf = conn.channel.writeAndFlush(byteBuffer); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (state == AsyncCommand.COMMAND_WRITE) { state = AsyncCommand.COMMAND_READ_HEADER; commandSentCounter++; } else { state = AsyncCommand.AUTH_READ_HEADER; } command.dataOffset = 0; // Socket timeout applies only to read events. // Reset event received because we are switching from a write to a read state. // This handles case where write succeeds and read event does not occur. If we didn't reset, // the socket timeout would go through two iterations (double the timeout) because a write // event occurred in the first timeout period. eventReceived = false; conn.channel.config().setAutoRead(true); } }); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { Channel ch = ctx.channel(); int sessionId = ch.attr(SESSION_ID).get(); int port = ch.attr(PORT).get(); if (e instanceof ConnectException) { UscError reply = new UscError(port, sessionId, UscError.ErrorCode.ECONNREFUSED.getCode()); plugin.writeAndFlush(reply); } else if (e instanceof PortUnreachableException) { UscError reply = new UscError(port, sessionId, UscError.ErrorCode.ENETUNREACH.getCode()); plugin.writeAndFlush(reply); } else { UscError reply = new UscError(port, sessionId, UscError.ErrorCode.E_OTHER.getCode()); plugin.writeAndFlush(reply); super.exceptionCaught(ctx, e); } }
public static void main(String []args) throws InterruptedException { new NettyServerBootstrap(18080); while (true){ SocketChannel channel=(SocketChannel)NettyChannelMap.get("001"); if(channel!=null){ AskMsg askMsg=new AskMsg(); channel.writeAndFlush(askMsg); } TimeUnit.SECONDS.sleep(5); } }
public static void main(String []args) throws InterruptedException { NettyServerBootstrap bootstrap=new NettyServerBootstrap(9999); while (true){ SocketChannel channel=(SocketChannel)NettyChannelMap.get("001"); if(channel!=null){ AskMsg askMsg=new AskMsg(); channel.writeAndFlush(askMsg); } TimeUnit.SECONDS.sleep(10); } } }
private void writeByteBuffer() { ByteBuf byteBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(command.dataOffset); byteBuffer.clear(); byteBuffer.writeBytes(command.dataBuffer, 0, command.dataOffset); ChannelFuture cf = conn.channel.writeAndFlush(byteBuffer); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (state == AsyncCommand.COMMAND_WRITE) { state = AsyncCommand.COMMAND_READ_HEADER; commandSentCounter++; } else { state = AsyncCommand.AUTH_READ_HEADER; } command.dataOffset = 0; // Socket timeout applies only to read events. // Reset event received because we are switching from a write to a read state. // This handles case where write succeeds and read event does not occur. If we didn't reset, // the socket timeout would go through two iterations (double the timeout) because a write // event occurred in the first timeout period. eventReceived = false; conn.channel.config().setAutoRead(true); } }); }
public static void login(SocketChannel socketChannel, String uuid) { try { LoginMsg loginMsg = new LoginMsg(); loginMsg.setClientId(uuid); loginMsg.setUserName("wuhf"); loginMsg.setPassword("abcd"); socketChannel.writeAndFlush(loginMsg); } catch (Exception e) { e.printStackTrace(); } }
private void processWriteRequest(WriteRequest toProcess) { final String methodName = "processWriteRequest"; logger.entry(this, methodName, toProcess); final Promise<Boolean> writeCompletePromise = toProcess.promise; logger.data(this, methodName, "writeAndFlush {}", toProcess); final ChannelFuture f = channel.writeAndFlush(toProcess.buffer); f.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { boolean havePendingWrites; synchronized(pendingWrites) { writeInProgress = false; havePendingWrites = !pendingWrites.isEmpty(); } logger.data(this, methodName, "doWrite (complete)"); writeCompletePromise.setSuccess(!havePendingWrites); doWrite(); } }); logger.exit(this, methodName); }
@Override public void channelActive(ChannelHandlerContext ctx) { super.channelActive(ctx); SocketChannel channel = (SocketChannel) ctx.channel(); component.channels.addLocalSocket(channel); InetSocketAddress other = channel.remoteAddress(); DisambiguateConnection r = new DisambiguateConnection(component.self, new NettyAddress(other), protocol, component.boundUDTPort, true); channel.writeAndFlush(r); } }
public static void main(String[]args) throws InterruptedException { Constants.setClientId("001"); NettyClientBootstrap bootstrap=new NettyClientBootstrap(9999,"localhost"); LoginMsg loginMsg=new LoginMsg(); loginMsg.setPassword("yao"); loginMsg.setUserName("robin"); bootstrap.socketChannel.writeAndFlush(loginMsg); while (true){ TimeUnit.SECONDS.sleep(3); AskMsg askMsg=new AskMsg(); AskParams askParams=new AskParams(); askParams.setAuth("authToken"); askMsg.setParams(askParams); bootstrap.socketChannel.writeAndFlush(askMsg); } } }
public static void main(String[] args) throws InterruptedException { Constants.setClientId("001"); NettyClientBootstrap bootstrap = new NettyClientBootstrap(18080, "localhost"); LoginMsg loginMsg = new LoginMsg(); loginMsg.setPassword("yao"); loginMsg.setUserName("robin"); bootstrap.socketChannel.writeAndFlush(loginMsg); while (true) { TimeUnit.SECONDS.sleep(3); AskMsg askMsg = new AskMsg(); AskParams askParams = new AskParams(); askParams.setAuth("authToken"); askMsg.setParams(askParams); bootstrap.socketChannel.writeAndFlush(askMsg); } }
component.extLog.trace("Finally sending Disamb: {}", dc); waitingForCreationUDT.add(destination.asSocket()); sc.writeAndFlush(new MessageWrapper(dc));
ch.writeAndFlush(greetingBuffer);
@Override public Publisher<Void> apply(ChannelStream<IN, OUT> ch) { NettyHttpChannel<IN, OUT> request = (NettyHttpChannel<IN, OUT>) ch; if (handler != null) { handler.apply(request); } Iterable<? extends Publisher<Void>> handlers = routeChannel(request); //404 if (handlers == null) { if (request.checkHeader()) { request.delegate().writeAndFlush( new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND)); } return Streams.empty(); } return Streams.concat(handlers); } });
minsc.writeAndFlush(new MessageNotify.Req(new CheckChannelActive(component.self, msg.getSource(), Transport.TCP)));