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;未經允許,請勿轉載。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/298104.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

被娱乐在线报道的“唐骏造假门事件”

最近全球最热的是南非的世界杯&#xff0c;而在中国最近比较热的是另外一个事情。。。话说那天晚上回家已经很晚&#xff0c;照例的&#xff0c;家里的毛孩子歪歪斜斜的睡在床的角落里&#xff0c;一边是正在看节目的老婆吃着零食&#xff0c;我随便瞄了一眼&#xff0c;是新闻…

16年微软/腾讯云/华为云MVP是怎样炼成的

自由、创新、研究、探索&#xff0c;很难想象到一个IT大神的博客&#xff0c;会将“自由”放在第一位&#xff0c;也许这二字代表的&#xff0c;既是精神&#xff0c;又是情怀。搞微软技术的&#xff0c;大家或多或少都有听说过微软的“最有价值专家”&#xff08;MVP&#xff…

Dave Python 练习三 -- 对象

#encodingutf-8 #*************Part 1 : 对象 ****************** #Python 对象 #Python 使用对象模型来存储数据。构造任何类型的值都是一个对象。所有的Python 对像都拥有三个特性&#xff1a;身份&#xff0c;类型和值。 #身份&#xff1a; #每一个对象都有一个唯一的身份标…

java 注册驱动失败_java – JDBC驱动程序注册死锁?

在一个线程中,正在创建一个JackRabbit&#xff1a;"docs-on-startup" #32 prio5 os_prio0 tid0x00007f730d73e800 nid0x601d in Object.wait() [0x00007f725bffc000]java.lang.Thread.State: RUNNABLEat sun.reflect.NativeConstructorAccessorImpl.newInstance0(Nat…

python3多线程queue_Python多线程(3)——Queue模块

Queue模块支持先进先出(FIFO)队列&#xff0c;支持多线程的访问&#xff0c;包括一个主要的类型(Queue)和两个异常类(exception classes)。Python 2 中的Queue模块在Python 3中更名为 queue。Queue对象的创建可以通过实例化Queue类型获得队列对象&#xff1a;创建新的队列&…

.NET中的设计模式---由吃龙虾想到的

作者: 倪大虾 发表于 2010-07-18 18:10 原文链接 阅读: 725 评论: 20今天吃小龙虾的时候忽然想到了以前一个湖北朋友讲的虾的故事.这位朋友是湖北人,据他说在他小时候他们那里很多虾,特别是夏天雨后,满地爬的都是.因为传说那是美国对付中国的秘密武器,居然没有人敢吃.后来偶然有…

【需要重视的BUG】:偷权限的情况

&#xff01;&#xff01;如果您生产环境用到了Blog.Core系统&#xff08;本文是我自己逻辑问题&#xff0c;和官方没关系哈&#xff09;&#xff0c;且没有做其他修改&#xff0c;且没有使用Ids4认证中心来授权认证&#xff0c;请看完本文&#xff0c;并即时做系统维护。-----…

Java实现文件过滤

Java实现文件过滤的方法&#xff0c;比如我只想获得某个路径下.java文件 只需要实现FilenameFilter这个接口即可。 比如&#xff1a; private class FileFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.en…

Angular运行在java_在本地运行现有Angular项目

我是Angular的新手&#xff0c;我正在尝试在我的机器上运行Angular的现有项目 . 我做了很多测试并且跟着很多文章 . 但无法运行我的项目 .我有这样的项目文件&#xff1a;我在我的系统上安装了nodejs . 并根据文章按照以下说明操作&#xff1a;将目录更改为我们的仓库cd myproj…

python作业题目用户输入行数、输出倒的等腰三角形_智慧职教云课堂APPPython程序设计(常州工业职业技术学院)作业期末考试答案...

在FANUC15系统中所采用的高分辨率绝对脉冲编码器&#xff0c;若每转输出脉冲数为100万个&#xff0c;最高允许转速10000r&#xff0f;min。如果当前和今后相当长一段时期&#xff0c;个人住房贷款市场中()将是一种主要的模式。A.多种机构的参与菱形ABCD中&#xff0c;AB2&#…

自找麻烦

2019独角兽企业重金招聘Python工程师标准>>> 真是想狗想的要发疯了&#xff0c;所以想买条狗&#xff0c;但是阿拉斯加&#xff0c;哈士奇&#xff0c;金毛&#xff0c;拉布拉多&#xff0c;苏牧&#xff0c;喜乐蒂现在我都买不起&#xff0c;他们都是很听话的狗&am…

Prism+WPF使用DependencyInjection实现AutoMapper的依赖注入功能

前言在使用PRISMWPF开发项目的过程中&#xff0c;需要使用AutoMapper实现对象-对象的映射功能。无奈PRISM没有相关对AutoMapper相关的类库&#xff0c;于是转换一下思想&#xff0c;在nuget 中存在有关使用Microsoft.Extensions.DependencyInjection来实现AutoMapper的依赖注入…

【机房真是】。。。各种蛋疼。。。

渣渣。。。呵呵。。。预流推进什么的。。。呵呵。。。。渣渣。。。渣渣。。。、、走了。。。 转载于:https://www.cnblogs.com/Aoi3x/archive/2011/09/07/2645360.html

webSocket原理及其案例

常见的消息推送方式 1&#xff1a;轮询方式 浏览器以指定的时间间隔向服务器发出HTTP请求&#xff0c;服务器实现试试返回数据给浏览器 缺点&#xff1a;数据有延时、服务器压力较大。 2&#xff1a;长轮询 浏览器发出ajax&#xff08;异步&#xff09;请求&#xff0c;服…

这是啥?也太秀了吧?

1 请坐下2 这是什么愿望&#xff0c;感觉老天都看不下去了&#xff01;3 像极了手机落在上铺的你&#xff01;4 真正智慧家居&#xff0c;免通电。5 你以为它是土豆&#xff0c;其实。。6 葫芦不一定叫葫芦葫芦有各种奇奇怪怪的形状和名字7 我发光去了&#xff01;你点的每个赞…

php七牛分片上传_利用七牛的php SDK分片上传时如何处理Notify?

我的代码如下&#xff0c;有填写相应的Rio_PutExtra&#xff0c;但是进度貌似没有输出来&#xff1f;请问是哪里写的不对么&#xff1f;…function upload($bucket, $key, $file, $type"file"){$qiniu_key "…AK…";$qiniu_sec "…SK…";Qiniu…

python课程思路_学习python课程第二十六天

一. 传输层在上述三层协议中我们,ip协议帮我们定位到子网络. mac地址帮我们定位到一台计算机,并与其通讯,但本质上,计算机的通讯是为了应用程序能够通讯,而一台计算机上不可能运行一个应用程序问题:就像我们同时运行QQ软件和微信软件, 当计算机收到一个数据包时, 需要知道这…

爱数应用容灾部署方案三

级联复制的异地容灾方案部署 爱数应用容灾部署方案可在异地部署远程容灾站点实现远程应用容灾方案&#xff0c;采用级联复制模型&#xff0c;在本地和远程分别部署容灾站点&#xff0c;克服实时复制对带宽延迟较高的缺点&#xff0c;获得最佳的容灾效果。并且可根据用户的网络和…

c# 按位与,按位或

最近在园子里看到了这篇文章&#xff0c;看完这篇会有意外收获&#xff1a;C#枚举高级战术https://mp.weixin.qq.com/s/yipaL6Acil-uxq_bDDgdyg想起了很久之前的自己的一篇总结&#xff0c;特地找出来------在工作中遇到按位或组合权限串。一直不是特别明白。今天终于花了半个下…

poj3160

http://poj.org/problem?id3160 题意读懂是关键&#xff0c;he chould choose to enter and give out a gift and hear the words from the recipient, or bypass the room in silence.通过这句话知道当收礼者给予的反应是负值时可以不加&#xff0c;flymouse decided to choo…