Java Code Examples for org.jboss.netty.bootstrap.ClientBootstrap

The following examples show how to use org.jboss.netty.bootstrap.ClientBootstrap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: dubbo-2.6.5   Author: tianheframe   File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #2
Source Project: dubbox   Author: learningtcc   File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #3
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 文件上传
 * @param file 需要上传的文件
 * @param fileName 文件名称
 * @param thumbMark 是否需要生成缩略图
 * @return
 * @author:landyChris
 */
public static String uploadFile(File file, String fileName,
		boolean thumbMark) {
	FileClientPipelineFactory clientPipelineFactory = new FileClientPipelineFactory();
	//辅助类。用于帮助我们创建NETTY服务
	ClientBootstrap bootstrap = createClientBootstrap(clientPipelineFactory);
	String strThumbMark = Constants.THUMB_MARK_NO;
	if (thumbMark) {
		strThumbMark = Constants.THUMB_MARK_YES;
	}
	//具体处理上传文件逻辑
	uploadFile(bootstrap, FileClientContainer.getHost(),
			FileClientContainer.getPort(), file, fileName, strThumbMark,
			FileClientContainer.getUserName(),
			FileClientContainer.getPassword());
	Result result = clientPipelineFactory.getResult();
	if ((result != null) && (result.isCode())) {
		return result.getFilePath();
	}
	return null;
}
 
Example #4
Source Project: dubbox-hystrix   Author: yunhaibin   File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #5
Source Project: hadoop   Author: naver   File: SimpleTcpClient.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  // Configure the client.
  ChannelFactory factory = new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
  ClientBootstrap bootstrap = new ClientBootstrap(factory);

  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(setPipelineFactory());

  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);

  // Start the connection attempt.
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

  if (oneShot) {
    // Wait until the connection is closed or the connection attempt fails.
    future.getChannel().getCloseFuture().awaitUninterruptibly();

    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
  }
}
 
Example #6
Source Project: big-c   Author: yncxcw   File: SimpleTcpClient.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  // Configure the client.
  ChannelFactory factory = new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
  ClientBootstrap bootstrap = new ClientBootstrap(factory);

  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(setPipelineFactory());

  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);

  // Start the connection attempt.
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

  if (oneShot) {
    // Wait until the connection is closed or the connection attempt fails.
    future.getChannel().getCloseFuture().awaitUninterruptibly();

    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
  }
}
 
Example #7
Source Project: dubbo3   Author: linux-china   File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(() -> {
        NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("decoder", adapter.getDecoder());
        pipeline.addLast("encoder", adapter.getEncoder());
        pipeline.addLast("handler", nettyHandler);
        return pipeline;
    });
}
 
Example #8
Source Project: dubbox   Author: hutai123   File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #9
Source Project: anima   Author: qiuhd2015   File: NettyClient.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doOpen() throws Throwable {
	bootstrap = new ClientBootstrap(channelFactory);
	bootstrap.setOption("keepAlive", true);
	bootstrap.setOption("tcpNoDelay", true);
	bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
	final NettyHandler nettyHandler = new NettyHandler(getConf(), this);
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() {
			NettyCodecAdapter adapter = new NettyCodecAdapter(getConf(),getCodec(), NettyClient.this);
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("decoder", adapter.getDecoder());
			pipeline.addLast("encoder", adapter.getEncoder());
			pipeline.addLast("handler", nettyHandler);
			return pipeline;
		}
	});
}
 
Example #10
Source Project: floodlight_with_topoguard   Author: xuraylei   File: RPCService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Connect to remote servers.  We'll initiate the connection to
 * any nodes with a lower ID so that there will be a single connection
 * between each pair of nodes which we'll use symmetrically
 */
protected void startClients(ChannelPipelineFactory pipelineFactory) {
    final ClientBootstrap bootstrap =
            new ClientBootstrap(
                 new NioClientSocketChannelFactory(bossExecutor,
                                                   workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", CONNECT_TIMEOUT);
    bootstrap.setPipelineFactory(pipelineFactory);
    clientBootstrap = bootstrap;

    ScheduledExecutorService ses = 
            syncManager.getThreadPool().getScheduledExecutor();
    reconnectTask = new SingletonTask(ses, new ConnectTask());
    reconnectTask.reschedule(0, TimeUnit.SECONDS);
}
 
Example #11
Source Project: floodlight_with_topoguard   Author: xuraylei   File: Bootstrap.java    License: Apache License 2.0 6 votes vote down vote up
public void init() throws SyncException {
    cg = new DefaultChannelGroup("Cluster Bootstrap");

    bossExecutor = Executors.newCachedThreadPool();
    workerExecutor = Executors.newCachedThreadPool();

    bootstrap =
            new ClientBootstrap(new NioClientSocketChannelFactory(bossExecutor,
                                                                  workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.receiveBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", 
                        RPCService.CONNECT_TIMEOUT);
    pipelineFactory = new BootstrapPipelineFactory(this);
    bootstrap.setPipelineFactory(pipelineFactory);
}
 
Example #12
Source Project: floodlight_with_topoguard   Author: xuraylei   File: RemoteSyncManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void startUp(FloodlightModuleContext context) 
        throws FloodlightModuleException {
    shutdown = false;
    bossExecutor = Executors.newCachedThreadPool();
    workerExecutor = Executors.newCachedThreadPool();
    
    final ClientBootstrap bootstrap =
            new ClientBootstrap(
                 new NioClientSocketChannelFactory(bossExecutor,
                                                   workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.receiveBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", 
                        RPCService.CONNECT_TIMEOUT);
    pipelineFactory = new RemoteSyncPipelineFactory(this);
    bootstrap.setPipelineFactory(pipelineFactory);
    clientBootstrap = bootstrap;
}
 
Example #13
Source Project: dubbox   Author: remoting   File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #14
Source Project: vmstats   Author: Nordstrom   File: NettyTCPWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void connect() throws IOException {
    this.bootstrap = new ClientBootstrap(
            new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    this.bootstrap.setPipelineFactory(new NettyTCPWriterPipelineFactory(this.bootstrap, this.channel, this.timer));
    //this.bootstrap.setOption("tcpNoDelay", true);
    
    // TODO: do some exception handling here
    bootstrap.setOption("remoteAddress", new InetSocketAddress(this.host, this.port));
    this.future = this.bootstrap.connect();
    this.channel = this.future.awaitUninterruptibly().getChannel();
    this.channel.setReadable(false);
    
    if(!this.future.isSuccess()){
        logger.info("NettyTCP: future unsuccessful");
    }
}
 
Example #15
Source Project: incubator-tajo   Author: apache   File: Fetcher.java    License: Apache License 2.0 6 votes vote down vote up
public Fetcher(URI uri, File file, ClientSocketChannelFactory factory) {
  this.uri = uri;
  this.file = file;

  String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
  this.host = uri.getHost() == null ? "localhost" : uri.getHost();
  this.port = uri.getPort();
  if (port == -1) {
    if (scheme.equalsIgnoreCase("http")) {
      this.port = 80;
    } else if (scheme.equalsIgnoreCase("https")) {
      this.port = 443;
    }
  }

  bootstrap = new ClientBootstrap(factory);
  bootstrap.setOption("connectTimeoutMillis", 5000L); // set 5 sec
  bootstrap.setOption("receiveBufferSize", 1048576); // set 1M
  bootstrap.setOption("tcpNoDelay", true);

  ChannelPipelineFactory pipelineFactory = new HttpClientPipelineFactory(file);
  bootstrap.setPipelineFactory(pipelineFactory);
}
 
Example #16
Source Project: incubator-tajo   Author: apache   File: NettyClientBase.java    License: Apache License 2.0 6 votes vote down vote up
public void init(InetSocketAddress addr, ChannelPipelineFactory pipeFactory, ClientSocketChannelFactory factory)
    throws IOException {
  try {
    this.bootstrap = new ClientBootstrap(factory);
    this.bootstrap.setPipelineFactory(pipeFactory);
    // TODO - should be configurable
    this.bootstrap.setOption("connectTimeoutMillis", 10000);
    this.bootstrap.setOption("connectResponseTimeoutMillis", 10000);
    this.bootstrap.setOption("receiveBufferSize", 1048576 * 10);
    this.bootstrap.setOption("tcpNoDelay", true);
    this.bootstrap.setOption("keepAlive", true);

    connect(addr);
  } catch (Throwable t) {
    close();
    throw new IOException(t.getCause());
  }
}
 
Example #17
Source Project: onos   Author: opennetworkinglab   File: BgpControllerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
  * Starts the BGP peer.
  *
  * @param connectToSocket the socket to connect to
  */
 private void connect(InetSocketAddress connectToSocket)
     throws InterruptedException {

     ChannelFactory channelFactory =
         new NioClientSocketChannelFactory(
                 Executors.newCachedThreadPool(),
                 Executors.newCachedThreadPool());
     ChannelPipelineFactory pipelineFactory = () -> {
         ChannelPipeline pipeline = Channels.pipeline();
         pipeline.addLast("BgpPeerFrameDecoderTest",
                 peerFrameDecoder);
         pipeline.addLast("BgpPeerChannelHandlerTest",
                 peerChannelHandler);
         return pipeline;
     };

     peerBootstrap = new ClientBootstrap(channelFactory);
     peerBootstrap.setOption("child.keepAlive", true);
     peerBootstrap.setOption("child.tcpNoDelay", true);
     peerBootstrap.setPipelineFactory(pipelineFactory);
     peerBootstrap.connect(connectToSocket);
}
 
Example #18
Source Project: onos   Author: opennetworkinglab   File: BgpControllerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
private Channel connectFrom(InetSocketAddress connectToSocket, SocketAddress localAddress)
     throws InterruptedException {

     ChannelFactory channelFactory =
         new NioClientSocketChannelFactory(
                 Executors.newCachedThreadPool(),
                 Executors.newCachedThreadPool());
     ChannelPipelineFactory pipelineFactory = () -> {
         ChannelPipeline pipeline = Channels.pipeline();
         pipeline.addLast("BgpPeerFrameDecoderTest",
                 peerFrameDecoder);
         pipeline.addLast("BgpPeerChannelHandlerTest",
                 peerChannelHandler);
         return pipeline;
     };

     peerBootstrap = new ClientBootstrap(channelFactory);
     peerBootstrap.setOption("child.keepAlive", true);
     peerBootstrap.setOption("child.tcpNoDelay", true);
     peerBootstrap.setPipelineFactory(pipelineFactory);
     Channel channel = peerBootstrap.connect(connectToSocket, localAddress).getChannel();
     return channel;
}
 
Example #19
Source Project: elasticsearch-helper   Author: jprante   File: HttpInvoker.java    License: Apache License 2.0 6 votes vote down vote up
public HttpInvoker(Settings settings, ThreadPool threadPool, Headers headers, URL url) {
    super(settings, threadPool, headers);
    this.contexts = new HashMap<>();
    this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));
    bootstrap.setPipelineFactory(new HttpInvoker.HttpClientPipelineFactory());
    bootstrap.setOption("tcpNoDelay", true);

    registerAction(BulkAction.INSTANCE, HttpBulkAction.class);
    registerAction(CreateIndexAction.INSTANCE, HttpCreateIndexAction.class);
    registerAction(RefreshAction.INSTANCE, HttpRefreshIndexAction.class);
    registerAction(ClusterUpdateSettingsAction.INSTANCE, HttpClusterUpdateSettingsAction.class);
    registerAction(UpdateSettingsAction.INSTANCE, HttpUpdateSettingsAction.class);
    registerAction(SearchAction.INSTANCE, HttpSearchAction.class);

    this.url = url;
}
 
Example #20
Source Project: Flink-CEPplus   Author: ljygz   File: NetworkFailureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example #21
Source Project: flink   Author: flink-tpc-ds   File: NetworkFailureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example #22
Source Project: voyage   Author: zhaoshiling1017   File: NettyRpcConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * @param connectStatus 心跳检测状态是否正常
	 * @throws Throwable
	 */
	public void open(boolean connectStatus) throws Throwable {
		logger.info("open start,"+getConnStr());
		bootstrap = new ClientBootstrap(factory);
//		timer = new HashedWheelTimer();
		{
			bootstrap.setOption("tcpNoDelay", Boolean.parseBoolean(clientConfig.getTcpNoDelay()));
			bootstrap.setOption("reuseAddress", Boolean.parseBoolean(clientConfig.getReuseAddress()));
			bootstrap.setOption("SO_RCVBUF",1024*128);
			bootstrap.setOption("SO_SNDBUF",1024*128);
			bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
				public ChannelPipeline getPipeline() {
					ChannelPipeline pipeline = Channels.pipeline();
//					int readTimeout = clientConfig.getReadTimeout();
//					if (readTimeout > 0) {
//						pipeline.addLast("timeout", new ReadTimeoutHandler(timer,
//								readTimeout, TimeUnit.MILLISECONDS));
//					}
					pipeline.addLast("encoder", new RpcRequestEncode());
					pipeline.addLast("decoder", new RpcResponseDecode());
					pipeline.addLast("handler", NettyRpcConnection.this);
					return pipeline;
				}
			});
		}
		connected.set(connectStatus);
		logger.info("open finish,"+getConnStr());
	}
 
Example #23
Source Project: java-codes   Author: lihengming   File: HelloClient.java    License: MIT License 5 votes vote down vote up
public static void main(String args[]) {
    // Client服务启动器
    ClientBootstrap bootstrap = new ClientBootstrap(
            new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));
    // 设置一个处理服务端消息和各种消息事件的类(Handler)
    bootstrap.setPipelineFactory(() -> Channels.pipeline(new HelloClientHandler()));
    // 连接到本地的8000端口的服务端
    bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
}
 
Example #24
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
private static ClientBootstrap createClientBootstrap(
		FileClientPipelineFactory clientPipelineFactory) {
	ClientBootstrap bootstrap = new ClientBootstrap(
			new NioClientSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	bootstrap.setPipelineFactory(clientPipelineFactory);

	return bootstrap;
}
 
Example #25
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void uploadFile(ClientBootstrap bootstrap, String host,
		int port, File file, String fileName, String thumbMark,
		String userName, String pwd) {
	//1.构建uri对象
	URI uri = getUri(host, port);
	//2.连接netty服务端
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	//3.异步获取Channel对象
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}
	//4.初始化文件上传句柄对象
	WrapFileClientHandler handler = new UploadFileClientHandler(host, uri,
			file, fileName, thumbMark, userName, pwd);
	//5.获取Request对象
	HttpRequest request = handler.getRequest();
	//6.获取Http数据处理工厂
	HttpDataFactory factory = getHttpDataFactory();
	//7.进行数据的包装处理,主要是进行上传文件所需要的参数的设置,此时调用的句柄是具体的UploadFileClientHandler对象
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	//8.把request写到管道中,传输给服务端
	channel.write(request);
	//9.做一些关闭资源的动作
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();

	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example #26
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void deleteFile(ClientBootstrap bootstrap, String host,
		int port, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new DeleteFileClientHandler(host, uri,
			filePath, userName, pwd);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example #27
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 文件删除
 * @param filePath 文件服务器存储的文件路径(相对路径)
 * @param userName
 * @param pwd
 * @return
 * @author:landyChris
 */
public static boolean deleteFile(String filePath, String userName,
		String pwd) {
	FileClientPipelineFactory clientPipelineFactory = new FileClientPipelineFactory();
	ClientBootstrap bootstrap = createClientBootstrap(clientPipelineFactory);
	deleteFile(bootstrap, FileClientContainer.getHost(),
			FileClientContainer.getPort(), filePath, userName, pwd);
	Result result = clientPipelineFactory.getResult();
	if ((result != null) && (result.isCode())) {
		return result.isCode();
	}
	return false;
}
 
Example #28
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void replaceFile(ClientBootstrap bootstrap, String host,
		int port, File file, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new ReplaceFileClientHandler(host, uri,
			filePath, file, userName, pwd);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example #29
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 替换文件
 * @param file 需要替换的文件
 * @param filePath 文件服务器存储的文件路径(相对路径)
 * @return
 * @author:landyChris
 */
public static boolean replaceFile(File file, String filePath) {
	FileClientPipelineFactory clientPipelineFactory = new FileClientPipelineFactory();
	ClientBootstrap bootstrap = createClientBootstrap(clientPipelineFactory);
	replaceFile(bootstrap, FileClientContainer.getHost(),
			FileClientContainer.getPort(), file, filePath,
			FileClientContainer.getUserName(),
			FileClientContainer.getPassword());
	Result result = clientPipelineFactory.getResult();
	if ((result != null) && (result.isCode())) {
		return result.isCode();
	}

	return false;
}
 
Example #30
Source Project: netty-file-parent   Author: landy8530   File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void createThumbPicture(ClientBootstrap bootstrap,
		String host, int port, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new CreateThumbPictureClientHandler(
			host, uri, userName, pwd, filePath);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}