當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。