当前位置: 首页>>代码示例>>Java>>正文


Java SocketChannel类代码示例

本文整理汇总了Java中io.netty.channel.socket.SocketChannel的典型用法代码示例。如果您正苦于以下问题:Java SocketChannel类的具体用法?Java SocketChannel怎么用?Java SocketChannel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SocketChannel类属于io.netty.channel.socket包,在下文中一共展示了SocketChannel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: EchoClient

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
public EchoClient(String host, int port) {
    EventLoopGroup worker = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();

    b.group(worker)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline()
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(ech);
                }
            });

    b.connect(host, port);
}
 
开发者ID:AlphaHelixDev,项目名称:AlphaLibary,代码行数:21,代码来源:EchoClient.java

示例2: createRpcClientRTEDuringConnectionSetup

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
protected AsyncRpcClient createRpcClientRTEDuringConnectionSetup(Configuration conf) {
  setConf(conf);
  return new AsyncRpcClient(conf, new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                throws Exception {
              promise.setFailure(new RuntimeException("Injected fault"));
            }
          });
        }
      });
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:17,代码来源:TestAsyncIPC.java

示例3: start

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
public void start() throws Exception {
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(new InetSocketAddress(this.host, this.port))
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						System.out.println("connected server...");
						ch.pipeline().addLast(new ByteArrayEncoder());
						ch.pipeline().addLast(new ByteArrayDecoder());
						ch.pipeline().addLast(new EchoClientHandler());
					}
				});

		ChannelFuture cf = b.connect().sync();

		cf.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully().sync();
	}
}
 
开发者ID:Him188,项目名称:JPRE,代码行数:25,代码来源:TestClient.java

示例4: openServer

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
public void openServer(URL url) throws Exception{
    EventLoopGroup eventLoop = new NioEventLoopGroup();
    EventLoopGroup workLoop = new NioEventLoopGroup();
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(eventLoop, workLoop);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>(){

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))) // in 1
                    .addLast("handler", new ServerHandler()) // in 2
                    .addLast("encoder", new ObjectEncoder()); // out 3

        }
    });
    serverChannel = serverBootstrap.bind(url.getPort()).sync().sync().channel();
    logger.info("start server at:" + url.getPort());
}
 
开发者ID:justice-code,项目名称:star-map,代码行数:23,代码来源:StarServerProtocol.java

示例5: bind

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
public void bind(int port) {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
    EventLoopGroup workerGroup = new NioEventLoopGroup();  
    ServerBootstrap bootstrap = new ServerBootstrap()
            .group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(8888))
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new Encoder(serializer), new Decoder(serializer), new ProviderHandler());
                }
                
            });
    
    bootstrap.bind(port);
}
 
开发者ID:DanceFirstThinkLater,项目名称:PetiteRPC,代码行数:19,代码来源:NettyAcceptor.java

示例6: init

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
public void init() {
    super.init();
    b.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(defLoopGroup,
                            new SdkServerDecoder(12),  // 自定义解码器
                            new SdkServerEncoder(),    // 自定义编码器
                            new SdkServerHandler(snowFlake) // 自定义处理器
                    );
                }
            });
}
 
开发者ID:beyondfengyu,项目名称:DistributedID,代码行数:22,代码来源:SdkServer.java

示例7: doOpen

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
public void doOpen() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast((SimpleChannelInboundHandler)handler);
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture future = serverBootstrap.bind(address,port).sync();
        //future.channel().closeFuture().sync();
    }finally{
        //workerGroup.shutdownGracefully();
        //bossGroup.shutdownGracefully();
    }
}
 
开发者ID:dachengxi,项目名称:mini-dubbo,代码行数:25,代码来源:NettyServer.java

示例8: initChannel

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new LoggingHandler());
    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    if (sslCtx != null)
        pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
开发者ID:veritasware,项目名称:neto,代码行数:22,代码来源:SecureChatClientInitializer.java

示例9: initChannel

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
/**
 * Initialize the {@code SocketChannel}.
 *
 * This method initializes a new channel created by the {@code ServerBootstrap}
 *
 * The default implementation create a remote connection, configures a default pipeline
 * which handles coding/decoding messages, handshaking, timeout and error handling based
 * on {@code RpcConfig} instance provided at construction time.
 *
 * Subclasses can override it to add extra handlers if needed.
 *
 * Note that this method might be called while the instance is still under construction.
 *
 * @param ch the socket channel
 */
protected void initChannel(final SocketChannel ch) {
  C connection = initRemoteConnection(ch);
  connection.setChannelCloseHandler(getCloseHandler(ch, connection));

  final ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(PROTOCOL_ENCODER, new RpcEncoder("s-" + rpcConfig.getName()));
  pipeline.addLast("message-decoder", getDecoder(connection.getAllocator()));
  pipeline.addLast("handshake-handler", getHandshakeHandler(connection));

  if (rpcConfig.hasTimeout()) {
    pipeline.addLast(TIMEOUT_HANDLER,
        new LogggingReadTimeoutHandler(connection, rpcConfig.getTimeout()));
  }

  pipeline.addLast("message-handler", new InboundHandler(connection));
  pipeline.addLast("exception-handler", new RpcExceptionHandler<>(connection));
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:33,代码来源:BasicServer.java

示例10: start

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
         .channel(NioSocketChannel.class)
         .remoteAddress(new InetSocketAddress(host, port))
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) 
                 throws Exception {
                 ch.pipeline().addLast(
                         new EchoClientHandler());
             }
         });

        ChannelFuture f = bootstrap.connect().sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
开发者ID:zy416548283,项目名称:NettyStudy,代码行数:24,代码来源:EchoClient.java

示例11: run

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
开发者ID:oes-network,项目名称:im,代码行数:24,代码来源:EchoServer.java

示例12: main

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new TcpRttDecoder())
                                .addLast(new TcpRttClientHandler(COUNT));
                    }
                }).option(ChannelOption.TCP_NODELAY, true);

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
 
开发者ID:szhnet,项目名称:kcp-netty,代码行数:27,代码来源:TcpRttClient.java

示例13: closeChannelGroup

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
private static CompletableFuture<Void> closeChannelGroup(
    ChannelGroup channelGroup, CloseType closeType) {
  switch (closeType) {
    case DISCONNECT:
      return completable(channelGroup.disconnect());
    default:
      return CompletableFuture.allOf(
          channelGroup
              .stream()
              .map(
                  c -> {
                    CompletableFuture<Void> f;
                    Function<SocketChannel, ChannelFuture> shutdownMethod =
                        closeType == CloseType.SHUTDOWN_READ
                            ? SocketChannel::shutdownInput
                            : SocketChannel::shutdownOutput;
                    if (c instanceof SocketChannel) {
                      f = completable(shutdownMethod.apply((SocketChannel) c));
                    } else {
                      logger.warn(
                          "Got {} request for non-SocketChannel {}, disconnecting instead.",
                          closeType,
                          c);
                      f = completable(c.disconnect());
                    }
                    return f;
                  })
              .collect(Collectors.toList())
              .toArray(new CompletableFuture[] {}));
  }
}
 
开发者ID:datastax,项目名称:simulacron,代码行数:32,代码来源:BoundNode.java

示例14: initChannel

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
protected void initChannel(SocketChannel channel) throws Exception {
	channel.pipeline()
			.addLast(new ReadTimeoutHandler(30))
			.addLast("splitter", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4))
			.addLast(new PacketDecoder())
			.addLast("prepender", new LengthFieldPrepender(4))
			.addLast(new PacketEncoder())
			.addLast(client.getHandler());
	this.client.setChannel(channel);
	System.out.println("Netty client started");
}
 
开发者ID:CentauriCloud,项目名称:CentauriCloud,代码行数:13,代码来源:OpenCloudChannelInitializer.java

示例15: connect

import io.netty.channel.socket.SocketChannel; //导入依赖的package包/类
@Override
public void connect() {
  checkState(channel == null, "channel already initialized");
  try {
    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init((KeyStore) null);
    final SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustFactory).build();
    Bootstrap bootstrap = new Bootstrap();
    final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            p.addLast(
                new HttpClientCodec(),
                // Set the max size for the HTTP responses. This only applies to the WebSocket
                // handshake response from the server.
                new HttpObjectAggregator(32 * 1024),
                channelHandler);
          }
        });

    ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
    this.channel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
              eventHandler.onError(future.cause());
            }
          }
        }
    );
  } catch (Exception e) {
    eventHandler.onError(e);
  }
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:44,代码来源:NettyWebSocketClient.java


注:本文中的io.netty.channel.socket.SocketChannel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。