java try finally connectoin close_Java SocketChannel類代碼示例
本文整理匯總了Java中io.netty.channel.socket.SocketChannel類的典型用法代碼示例。如果您正苦於以下問題:Java SocketChannel類的具體用法?Java SocketChannel怎麽用?Java SocketChannel使用的例子?那麽恭喜您, 這裏精選的類代碼示例或許可以為您提供幫助。
SocketChannel類屬於io.netty.channel.socket包,在下文中一共展示了SocketChannel類的40個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Java代碼示例。
示例1: EchoClient
點讚 3
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() {
@Override
protected void initChannel(SocketChannel socketChannel) {
socketChannel.pipeline()
.addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(ech);
}
});
b.connect(host, port);
}
開發者ID:AlphaHelixDev,項目名稱:AlphaLibary,代碼行數:21,
示例2: createRpcClientRTEDuringConnectionSetup
點讚 3
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
protected AsyncRpcClient createRpcClientRTEDuringConnectionSetup(Configuration conf) {
setConf(conf);
return new AsyncRpcClient(conf, new ChannelInitializer() {
@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,
示例3: start
點讚 3
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() {
@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,
示例4: openServer
點讚 3
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(){
@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,
示例5: bind
點讚 3
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() {
@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,
示例6: init
點讚 3
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() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(defLoopGroup,
new SdkServerDecoder(12), // 自定義解碼器
new SdkServerEncoder(), // 自定義編碼器
new SdkServerHandler(snowFlake) // 自定義處理器
);
}
});
}
開發者ID:beyondfengyu,項目名稱:DistributedID,代碼行數:22,
示例7: doOpen
點讚 3
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() {
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,
示例8: initChannel
點讚 3
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,
示例9: initChannel
點讚 3
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,
示例10: start
點讚 3
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() {
@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,
示例11: run
點讚 3
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() {
@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,
示例12: main
點讚 3
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() {
@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,
示例13: closeChannelGroup
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
private static CompletableFuture closeChannelGroup(
ChannelGroup channelGroup, CloseType closeType) {
switch (closeType) {
case DISCONNECT:
return completable(channelGroup.disconnect());
default:
return CompletableFuture.allOf(
channelGroup
.stream()
.map(
c -> {
CompletableFuture f;
Function 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,
示例14: initChannel
點讚 2
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,
示例15: connect
點讚 2
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() {
@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,
示例16: connect
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
/**
*@description 連接服務器
*@time 創建時間:2017年7月21日下午4:15:50
*@param host
*@param port
*@throws InterruptedException
*@author dzn
*/
public void connect(String host, int port) throws InterruptedException{
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap boot = new Bootstrap();
boot.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//增加以\n 和 \r\n為數據換行符的Handler
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
//增加字符串解析器
ch.pipeline().addLast(new StringDecoder());
//對輸入數據進行業務邏輯處理
ch.pipeline().addLast(new RightTimeClientHandler());
}
});
//連接服務器
ChannelFuture future = boot.connect(host, port).sync();
//等待客戶端Channel關閉
future.channel().closeFuture().sync();
}finally{
group.shutdownGracefully();
}
}
開發者ID:SnailFastGo,項目名稱:netty_op,代碼行數:40,
示例17: start
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
public void start() {
b.group(workGroup)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("SdkServerDecoder", new SdkClientDecoder(12))
.addLast("SdkServerEncoder", new SdkClientEncoder())
.addLast("SdkClientHandler", new SdkClientHandler());
}
});
try {
cf = b.connect(GlobalConfig.DEFAULT_HOST, GlobalConfig.SDKS_PORT).sync();
cf.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
logger.error("client channel close", channelFuture.cause());
shutdown();
}
});
InetSocketAddress address = (InetSocketAddress) cf.channel().remoteAddress();
logger.info("SdkClient start success, host is {}, port is {}", address.getHostName(),
address.getPort());
} catch (InterruptedException e) {
logger.error("SdkClient start error", e);
shutdown(); //關閉並釋放資源
}
}
開發者ID:beyondfengyu,項目名稱:DistributedID-SDK,代碼行數:35,
示例18: prepare
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override public void prepare(final Benchmark benchmark) {
this.concurrencyLevel = benchmark.concurrencyLevel;
this.targetBacklog = benchmark.targetBacklog;
ChannelInitializer channelInitializer = new ChannelInitializer() {
@Override public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
if (benchmark.tls) {
SslClient sslClient = SslClient.localhost();
SSLEngine engine = sslClient.sslContext.createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("handler", new HttpChannel(channel));
}
};
bootstrap = new Bootstrap();
bootstrap.group(new NioEventLoopGroup(concurrencyLevel))
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.channel(NioSocketChannel.class)
.handler(channelInitializer);
}
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:28,
示例19: createNetworkManagerAndConnect
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
/**
* Create a new NetworkManager from the server host and connect it to the server
*/
public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport)
{
final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
Class extends SocketChannel > oclass;
LazyLoadBase extends EventLoopGroup > lazyloadbase;
if (Epoll.isAvailable() && useNativeTransport)
{
oclass = EpollSocketChannel.class;
lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
}
else
{
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
}
catch (ChannelException var3)
{
;
}
p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder", (ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder", (ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
})).channel(oclass)).connect(address, serverPort).syncUninterruptibly();
return networkmanager;
}
開發者ID:sudofox,項目名稱:Backmemed,代碼行數:39,
示例20: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast("ssl-handler", sslCtx.newHandler(ch.alloc()));
}
//pipeline.addLast("http-compressor", new HttpContentCompressor());
pipeline.addLast("http-codec", new HttpServerCodec());
pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("http-chunked", new ChunkedWriteHandler());
pipeline.addLast("http-handler", new HttpFileServerHandler());
}
開發者ID:noti0na1,項目名稱:HFSN,代碼行數:13,
示例21: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new DefaultHttpServerHandler(ahsc));
}
開發者ID:uavorg,項目名稱:uavstack,代碼行數:10,
示例22: start
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public void start() throws InterruptedException {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_LINGER, socketLinger);
b.option(ChannelOption.SO_REUSEADDR, reuseAddress);
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpRequestDecoder());
p.addLast(new HttpObjectAggregator(1024 * 1024 * 5));
p.addLast(new HttpResponseEncoder());
p.addLast(new HttpContentCompressor());
if (corsConfiguration.hasHeader()) {
p.addLast(new CorsHandler(
CorsConfig
.withOrigin(corsConfiguration.getHeader())
.allowedRequestHeaders(HttpHeaders.Names.CONTENT_TYPE)
.allowedRequestMethods(HttpMethod.POST)
.build())
);
}
p.addLast(jsonRpcWeb3FilterHandler);
p.addLast(jsonRpcWeb3ServerHandler);
}
});
b.bind(host, port).sync();
}
開發者ID:rsksmart,項目名稱:rskj,代碼行數:31,
示例23: main
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public static void main(String[] args) throws Exception {
// Configure SSL.git
final SslContext sslCtx;
if (SSL) {
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
}
// p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new EchoClientHandler());
}
});
// 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:spafka,項目名稱:spark_deep,代碼行數:40,
示例24: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc(), ip, port));
}
pipeline.addLast(DECODER);
pipeline.addLast(ENCODER);
// and then business logic.
pipeline.addLast(CLIENT_HANDLER);
}
開發者ID:polarcoral,項目名稱:monica,代碼行數:15,
示例25: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
protected void initChannel(SocketChannel channel) throws Exception {
log.info("New channel created");
channel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
channel.pipeline().addLast(new MessageDecoder());
handleNewNodeConnection(channel);
}
開發者ID:shlee89,項目名稱:athena,代碼行數:8,
示例26: RemoteConnection
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public RemoteConnection(SocketChannel channel, String name, boolean blockOnSocket) {
super();
this.channel = channel;
this.clientName = name;
this.writeManager = new WriteManager();
this.requestIdMap = new RequestIdMap(getName());
if(!blockOnSocket){
writeManager.disable();
}
channel.pipeline().addLast(new BackPressureHandler());
}
開發者ID:dremio,項目名稱:dremio-oss,代碼行數:12,
示例27: start
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public void start() {
Configuration config = Configuration.INSTANCE;
InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline()
.addLast("logging", new LoggingHandler(LogLevel.DEBUG))
.addLast(new XConnectHandler());
if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
socketChannel.pipeline().addLast(
new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit())
);
}
}
});
log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol());
new Thread(() -> new UdpServer().start()).start();
ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getHost(), config.getPort()));
future.channel().closeFuture().sync();
} catch (Exception e) {
log.error("\tSocket bind failure ({})", e.getMessage());
} finally {
log.info("\tShutting down and recycling...");
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
Configuration.shutdownRelays();
}
System.exit(0);
}
開發者ID:ZhangJiupeng,項目名稱:AgentX,代碼行數:37,
示例28: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpClientCodec());
}
開發者ID:Sammers21,項目名稱:Ashbringer-load,代碼行數:11,
示例29: start
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
public void start() throws IOException, InterruptedException {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 0)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(
//new LoggingHandler(LogLevel.INFO)
new MsgEncoder(),
new MsgDecoder(),
new ServerHandler()
);
}
});
serverChannel = b.bind(this.port).sync().channel();
} finally {
}
}
開發者ID:altiplanogao,項目名稱:io-comparison,代碼行數:30,
示例30: start
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public static void start(MemberEventLoop loop) throws InterruptedException {
String host = "127.0.0.1";
int port = 9005;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
ch.pipeline().addLast(new ProtobufDecoder(SocketMessage.getDefaultInstance()));
ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
ch.pipeline().addLast(new ProtobufEncoder());
ch.pipeline().addLast(new IdleStateHandler(0, 5, 10, TimeUnit.SECONDS));
ch.pipeline().addLast(new BusinessRouterHandler(loop));
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
開發者ID:freedompy,項目名稱:commelina,代碼行數:38,
示例31: startSocket
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public void startSocket() throws InterruptedException {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap boot = new ServerBootstrap();
boot.group(boss,worker);
boot.channel(NioServerSocketChannel.class);
boot.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024*1024,0,4,-4,0,false));
ch.pipeline().addLast(new ByteToPacketCodec());
//ch.pipeline().addLast(new LoginChannelHandler(listener));
ch.pipeline().addLast(new PacketChannelHandler(listener));
}
});
boot.option(ChannelOption.SO_BACKLOG,128);
boot.childOption(ChannelOption.SO_KEEPALIVE,true);
channelFuture = boot.bind(port).sync();
System.out.println("服務器"+port+"開啟成功...");
channelFuture.channel().closeFuture().sync();
}finally {
boss.shutdownGracefully().sync();
worker.shutdownGracefully().sync();
channelFuture = null;
System.out.println("服務器關閉成功...");
}
}
開發者ID:werewolfKill,項目名稱:werewolf_server,代碼行數:32,
示例32: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline cp = socketChannel.pipeline();
cp.addLast(new HttpServerCodec()); //添加服務端http編、解碼器
cp.addLast(new HttpObjectAggregator(512*1024)); //http消息聚合
cp.addLast(new HttpContentCompressor()); //開啟壓縮
cp.addLast(new HttpServerHandler(kurdran));
}
開發者ID:togethwy,項目名稱:kurdran,代碼行數:9,
示例33: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(
new HttpServerCodec(),
new HttpServerExpectContinueHandler(),
new HttpObjectAggregator(Integer.MAX_VALUE),
new ChunkedWriteHandler(),
new HttpRequestHandler()
);
}
開發者ID:zhyzhyzhy,項目名稱:Ink,代碼行數:11,
示例34: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
protected void initChannel(final SocketChannel socketChannel) {
final ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(1048576 * 2, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ServerHandler());
}
開發者ID:dethi,項目名稱:guereza,代碼行數:11,
示例35: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
/**
* The Method that will initialize the channel.
*
* @param socketChannel The channel.
*
* @throws Exception Codec exception.
*/
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HTTPDecoder());
pipeline.addLast(new HTTPEncoder());
pipeline.addLast(new EchidnaConnection(socketChannel, server));
}
開發者ID:D3adspaceEnterprises,項目名稱:echidna,代碼行數:15,
示例36: Client
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
public Client ( final SocketAddress address, final ConnectionStateListener listener, final ProtocolOptions options, final List modules )
{
this.address = address;
this.options = options;
this.listener = listener;
this.manager = new MessageManager ( options );
this.group = new NioEventLoopGroup ();
this.bootstrap = new Bootstrap ();
this.bootstrap.group ( this.group );
this.bootstrap.channel ( NioSocketChannel.class );
this.bootstrap.handler ( new ChannelInitializer () {
@Override
protected void initChannel ( final SocketChannel ch ) throws Exception
{
handleInitChannel ( ch );
}
} );
this.modules = modules.toArray ( new ClientModule[modules.size ()] );
this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( "IEC60870Client/" + address ) );
for ( final ClientModule module : modules )
{
module.initializeClient ( this, this.manager );
}
}
開發者ID:eclipse,項目名稱:neoscada,代碼行數:33,
示例37: setUp
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Before
public void setUp()
throws Exception {
serverMock = new NioConnDroppingServer(DEFAULT_PORT, FAIL_EVERY_CONN_ATTEMPT);
final Semaphore concurrencyThrottle = new Semaphore(CONCURRENCY);
group = new NioEventLoopGroup();
final Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(
new ChannelInitializer() {
@Override
protected final void initChannel(final SocketChannel conn)
throws Exception {
conn.pipeline().addLast(new DummyClientChannelHandler());
}
}
)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.TCP_NODELAY, true);
connPool = new BasicMultiNodeConnPool(
concurrencyThrottle, NODES, bootstrap, CPH, DEFAULT_PORT, 0
);
connPool.preCreateConnections(CONCURRENCY);
}
開發者ID:akurilov,項目名稱:netty-connection-pool,代碼行數:29,
示例38: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("encoder", new MqttMessageEncoder());
pipeline.addLast("decoder", new MqttMessageDecoder());
pipeline.addLast("handler", new MqttMessageHandler());
}
開發者ID:osswangxining,項目名稱:mqttserver,代碼行數:8,
示例39: setupHttpChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {
return new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
ch.pipeline().addLast("encoder", new HttpResponseEncoder());
ch.pipeline().addLast("decoder", new HttpRequestDecoder());
ch.pipeline().addLast("compressor", new HttpContentCompressor());
ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
final Configuration.Cors corsCfg = config.getHttp().getCors();
final CorsConfig.Builder ccb;
if (corsCfg.isAllowAnyOrigin()) {
ccb = new CorsConfig.Builder();
} else {
ccb = new CorsConfig.Builder(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
}
if (corsCfg.isAllowNullOrigin()) {
ccb.allowNullOrigin();
}
if (corsCfg.isAllowCredentials()) {
ccb.allowCredentials();
}
corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
CorsConfig cors = ccb.build();
LOG.trace("Cors configuration: {}", cors);
ch.pipeline().addLast("cors", new CorsHandler(cors));
ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
ch.pipeline().addLast("strict", new StrictTransportHandler(config));
ch.pipeline().addLast("login", new X509LoginRequestHandler(config));
ch.pipeline().addLast("doLogin", new BasicAuthLoginRequestHandler(config));
ch.pipeline().addLast("error", new HttpExceptionHandler());
}
};
}
開發者ID:NationalSecurityAgency,項目名稱:qonduit,代碼行數:41,
示例40: initChannel
點讚 2
import io.netty.channel.socket.SocketChannel; //導入依賴的package包/類
protected void initChannel(SocketChannel socketChannel) {
socketChannel.pipeline()
.addLast(new AmqpDecoder())
.addLast(new AmqpEncoder())
.addLast(new AmqpConnectionHandler(configuration, broker))
.addLast(ioExecutors, new AmqpMessageWriter())
.addLast(ioExecutors, new BlockingTaskHandler());
}
開發者ID:wso2,項目名稱:message-broker,代碼行數:9,
注:本文中的io.netty.channel.socket.SocketChannel類示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。
java try finally connectoin close_Java SocketChannel類代碼示例相关推荐
- java cl 規格_Java JavaCL類代碼示例
本文整理匯總了Java中com.nativelibs4java.opencl.JavaCL類的典型用法代碼示例.如果您正苦於以下問題:Java JavaCL類的具體用法?Java JavaCL怎麽用? ...
- java datasource mysql_Java MysqlDataSource類代碼示例
本文整理匯總了Java中com.mysql.cj.jdbc.MysqlDataSource類的典型用法代碼示例.如果您正苦於以下問題:Java MysqlDataSource類的具體用法?Java M ...
- java uiautomation_Java UiAutomation類代碼示例
本文整理匯總了Java中android.app.UiAutomation類的典型用法代碼示例.如果您正苦於以下問題:Java UiAutomation類的具體用法?Java UiAutomation怎 ...
- java nifty_Java NiftyDialogBuilder類代碼示例
本文整理匯總了Java中com.gitonway.lee.niftymodaldialogeffects.NiftyDialogBuilder類的典型用法代碼示例.如果您正苦於以下問題:Java Ni ...
- java intfunction_Java IntFunction類代碼示例
本文整理匯總了Java中java.util.function.IntFunction類的典型用法代碼示例.如果您正苦於以下問題:Java IntFunction類的具體用法?Java IntFunct ...
- java sentence_Java Sentence類代碼示例
本文整理匯總了Java中aima.core.logic.propositional.parsing.ast.Sentence類的典型用法代碼示例.如果您正苦於以下問題:Java Sentence類的具 ...
- java中的case1怎么说_Java Cas20ServiceTicketValidator類代碼示例
本文整理匯總了Java中org.jasig.cas.client.validation.Cas20ServiceTicketValidator類的典型用法代碼示例.如果您正苦於以下問題:Java Ca ...
- java scene_Java Scene類代碼示例
本文整理匯總了Java中com.sun.j3d.loaders.Scene類的典型用法代碼示例.如果您正苦於以下問題:Java Scene類的具體用法?Java Scene怎麽用?Java Scene ...
- java notifier_Java Notifier類代碼示例
本文整理匯總了Java中org.apache.maven.model.Notifier類的典型用法代碼示例.如果您正苦於以下問題:Java Notifier類的具體用法?Java Notifier怎麽 ...
最新文章
- 抢占日本市场过程“苦不堪言”
- PHP中添加HTML代码的三种方法(printEND)
- Spring4.x新特性
- Mac下文件的编码及修改编码
- c性能大容量cket_5千左右预算,既轻薄(高颜值)又高性能的笔记本推荐(兼顾Pr剪辑、Ps修图、CAD制图、办公游戏)...
- python实验总结心得体会_如何更有效地“肝”论文?这里有份最全工具总结
- Apache部署django项目
- WorkTool(一)企业微信群管理机器人实现
- 史诗级互联网电商系统的演进过程详解
- android中一些特殊字符的使用(如:←↑→↓等箭头符号)
- 简述银行会计科目的分类
- IceCTF - All your Base are belong to us
- 2. 【containerd】 containerd-shim-runc-v1与 containerd-shim-runc-v2 区别
- 亲和图信息管理联想发散思维
- Java配置环境变量教程,Java配置环境变量的作用
- 网络虚拟化NSX学习笔记
- Cesium粒子系统、火焰粒子、喷水粒子
- 自制无线打印服务器tplink,TPLINK WR702N 改有线打印服务器 带LUCI管理页面(4M闪存 16M内存)...
- vc复制指定文件夹以及文件夹内的内容
- 《go程序语言设计》引言