本文整理汇总了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);
}
示例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"));
}
});
}
});
}
示例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();
}
}
示例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());
}
示例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);
}
示例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) // 自定义处理器
);
}
});
}
示例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();
}
}
示例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());
}
示例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));
}
示例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();
}
}
示例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();
}
}
示例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();
}
}
示例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[] {}));
}
}
示例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");
}
示例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);
}
}