`
chenhua_1984
  • 浏览: 1246394 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

netty的timeout

    博客分类:
  • java
阅读更多

客户端

 

 

package com.mchz.netty.test.client;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

/**
 * Sends one message when a connection is open and echoes back any received data
 * to the server. Simply put, the echo client initiates the ping-pong traffic
 * between the echo client and server by sending the first message to the
 * server.
 */
public class EchoClient extends Thread {

	private final String host;
	private final int port;
	private final int firstMessageSize;

	private Integer recyle = 5;

	public EchoClient(String host, int port, int firstMessageSize,
			String threadName) {
		this.host = host;
		this.port = port;
		this.firstMessageSize = firstMessageSize;
		System.out.println("current thread name is ====" + threadName);
		this.start();
	}

	public void run() {
		ClientBootstrap bootstrap = new ClientBootstrap(
				new NioClientSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new EchoClientHandler(
						firstMessageSize, recyle));
			}
		});

		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
				port));
		future.getChannel().getCloseFuture().awaitUninterruptibly();
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.releaseExternalResources();
	}

	public static void main(String[] args) throws Exception {
		int i = 1;
		while (true) {
			i++;
//			new EchoClient("172.16.4.123", 8080, 256, "thread=" + i);
			new EchoClient("127.0.0.1", 8080, 256, "thread=" + i);
			if (i > 3) {
				break;
			}
		}

		Thread.sleep(1000 * 200);
		System.out.println("end....");
	}
}

 

 

package com.mchz.netty.test.client;

import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;


/**
 * Handler implementation for the echo client. It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends SimpleChannelUpstreamHandler {

	private static final Logger logger = Logger
			.getLogger(EchoClientHandler.class.getName());
	private Integer recyle=5;
	private final ChannelBuffer firstMessage;
	private final AtomicLong transferredBytes = new AtomicLong();

	/**
	 * Creates a client-side handler.
	 */
	public EchoClientHandler(int firstMessageSize,Integer recyle) {
		
		this.recyle=recyle;
		if (firstMessageSize <= 0) {
			throw new IllegalArgumentException("firstMessageSize: "
					+ firstMessageSize);
		}
		firstMessage = ChannelBuffers.buffer(firstMessageSize);
		for (int i = 0; i < firstMessage.capacity(); i++) {
			firstMessage.writeByte((byte) i);
		}
	}

	public long getTransferredBytes() {
		return transferredBytes.get();
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		
		for (int i = 0; i < recyle; i++) {
			try {
				System.out.println("send a message to server ...");
				e.getChannel().write(firstMessage);
				Thread.sleep(5000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}


	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		// Close the connection when an exception is raised.
		System.out.println("close the connection when an exception is raised");
		logger.log(Level.WARNING, "Unexpected exception from downstream.",
				e.getCause());
		e.getChannel().close();
	}
}

 

服务端

 

    package com.mchz.netty.test.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

/**
 * Echoes back any received data from a client.
 */
public class EchoServer {

	private final int port;

	public EchoServer(int port) {
		this.port = port;
	}

	public void run() {
		// Configure the server.
		ServerBootstrap bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));

		ChannelPipelineFactory pipelineFactory = new MyPipelineFactory(
				new EchoServerHandler());
		bootstrap.setPipelineFactory(pipelineFactory);
//		bootstrap.setOption("allIdleTime", "10");
		
		bootstrap.bind(new InetSocketAddress(port));
	}

	public static void main(String[] args) throws Exception {
		int port;
		if (args.length > 0) {
			port = Integer.parseInt(args[0]);
		} else {
			port = 8080;
		}
		new EchoServer(port).run();
	}
}

 package com.mchz.netty.test.server;

import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
/**
 * Handler implementation for the echo server.
 */
public class EchoServerHandler extends IdleStateAwareChannelHandler  {

	private static final Logger logger = Logger
			.getLogger(EchoServerHandler.class.getName());
	private final AtomicLong transferredBytes = new AtomicLong();

	public long getTransferredBytes() {
		return transferredBytes.get();
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		System.out.println("server has been connected");
		super.channelConnected(ctx, e);
		
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		// Send back the received message to the remote peer.
		transferredBytes.addAndGet(((ChannelBuffer) e.getMessage())
				.readableBytes());
		System.out
				.println("I an server ,I received a message,and I will received a message after 5 mill later");
//		try {
//			Thread.sleep(5000);
//		} catch (InterruptedException e1) {
//			e1.printStackTrace();
//		}
//		e.getChannel().write(e.getMessage());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		// Close the connection when an exception is raised.
		System.out.println(" Close the connection when an exception is raised"+e.getCause().getMessage());
		logger.log(Level.WARNING, "Unexpected exception from downstream.",
				e.getCause());
		e.getChannel().close();
	}
	
	@Override
	public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
			throws Exception {
		
//		super.channelIdle(ctx, e);
		if( e.getState() == IdleState.ALL_IDLE){  
////            e.getChannel().write("str123".getBytes());  
            super.channelIdle(ctx, e);      
         }  
	}
	
	
}

 package com.mchz.netty.test.server;

import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;

public class MyPipelineFactory implements ChannelPipelineFactory {
	private ChannelHandler serverHandler;

	public MyPipelineFactory(ChannelHandler serverHander) {
		this.serverHandler = serverHander;
	}

	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline pipeline = Channels.pipeline();
		Timer timer = new HashedWheelTimer();
		pipeline.addLast("timeout", new ReadTimeoutHandler(timer, 10));
		pipeline.addLast("idleHandler", serverHandler);
		return pipeline;
	}

}
分享到:
评论

相关推荐

    NETTY权威指南部分源码

    "timeout" 和 "断掉重连" 是网络编程中的关键概念。在Netty中,我们可以利用IdleStateHandler来检测连接的空闲状态,并在超时后执行相应的操作,比如断开连接或者发起重连请求。这种机制对于保持网络服务的可靠性至...

    基于Java+netty内置时间轮工具处理大批量定时或超时任务工具源码.zip

    3. **任务接口与实现**:可能包含自定义的任务接口,如`Timeout`和`TimerTask`,需要了解它们的生命周期方法以及如何实现自己的业务逻辑。 4. **并发与线程安全**:因为`HashedWheelTimer`是线程安全的,所以理解其...

    akka-remote-transport-netty4:netty4 实现的 akka 远程传输

    startup-timeout = 10 s enabled-transports = ["akka.remote.netty4.tcp"] netty4 { tcp { port = 2554 } } } } } 之前的基准 Starting benchmark of 500000 messages with burst size 5000 and payload

    Netty空闲检测&Keepalive.pdf

    import io.netty.handler.timeout.IdleStateHandler; public class ServerIdleCheckHandler extends IdleStateHandler { public ServerIdleCheckHandler() { super(0, 0, 120, TimeUnit.SECONDS); // 设置120秒未...

    Nginx 上传大文件超时解决办法

    和client_header_timeout类似,如果客户端在这个时间内没有发送任何数据,Nginx也会返回408错误。 4. proxy_connect_timeout:设置与代理服务器连接的超时时间。当Nginx向代理服务器转发请求时,这个指令定义了等待...

    Xmodem和Ymodem 传输协议JAVA实现

    在IT领域,Xmodem和Ymodem是两种早期的文件传输协议,主要用于串行通信。这些协议在个人计算机发展的初期扮演了重要角色,尤其是在低带宽和不可靠的通信链路环境下。本文将深入探讨这两种协议的工作原理,并提供它们...

    junit.rar包

    8. **定时器测试**:`@Timeout`注解可以限制测试方法的执行时间,如果超过设定的时间,测试将失败。 9. **假设(Assumptions)**:JUnit 4引入了`org.junit.Assume`类,允许在测试开始前设置条件。如果假设失败,...

    Java时间轮算法的实现代码示例

    Java时间轮算法的核心思想是使用一个环形数组来存储定时任务,每个任务对应一个 timeout 对象,timeout 对象包含了任务的执行时间、任务的执行状态等信息。在每个 tick 时间点,Java时间轮算法会遍历环形数组,检查...

    总结下LoadRunner 接收Mismatch问题的处理办法

    - 例如,如果希望将超时时间设置为 1 秒,可以调用 `lrs_set_recv_timeout2(1, 0)`。 #### 四、使用 `MSG_PEEK` 标志 `MSG_PEEK` 是一个接收数据时的标志,它允许 LoadRunner 查看数据而不立即将其从接收队列中...

    java面试题_微服务--dubbo(41题).pdf

    在Provider上可以配置的Consumer端的属性有timeout、retries、loadbalance、actives等。 十三、Dubbo启动时如果依赖的服务不可用会怎样? Dubbo缺省会在启动时检查依赖的服务是否可用,不可用时会抛出异常,阻止...

    EasySocket:一个轻量级的Android端Socket框架,可快速实现客户端和服务端之间的TCP长连接通讯,兼容于各种消息协议,框架的特色之一是可以实现Socket的消息回调功能

    EasySocket README内容将不再更新,请到博客阅读最新的框架说明! 博客地址: EasySocket的初衷是希望使Socket编程变得更加简单、快捷,因此项目在实现了Socket基本功能的基础上,还实现了TCP层面的请求回调功能。...

    Java线程池学习资料-全

    `FutureTask`实现了`Future`接口,它内部维护了一个任务状态,任务发起者调用`get()`或`get(timeout)`方法获取结果时,如果任务尚未完成,会被阻塞等待。任务执行完成后,`FutureTask`会唤醒等待的线程。`cancel()`...

    spark单节点调优

    - `spark.rpc.askTimeout`:RPC请求超时时间,与`spark.network.timeout`配合调整。 - `spark.shuffle.blockTransferService`:选择合适的传输服务,如NIO或Netty,以提高数据传输速度。 7. **垃圾回收** - `...

    HornetQ集群配置

    &lt;refresh-timeout&gt;10000&lt;/refresh-timeout&gt; ``` ### 4. 复制策略 在主主集群中,数据复制是关键。HornetQ提供了多种复制策略,如全复制(Full Replication)和部分复制(Shared Store)。全复制中,所有节点...

    04.1、微服务--dubbo(41题)1

    8. Consumer端可配置属性:如timeout、retries、loadbalance和actives。 9. 启动时检查:Dubbo默认在启动时检查依赖服务,不可用时会抛出异常,可通过check="false"关闭此检查。 10. 序列化框架:推荐使用Hessian,...

    一个java tcp服务器的基础框架

    timeout.ms=30000 ``` 开发者可以根据实际需求调整这些参数,优化服务器性能。 四、依赖库(libs) `libs`目录通常包含项目运行所需的外部依赖库。在Java项目中,这可能是JAR文件,包含了如NIO、网络通信、序列化等...

    深入理解Spring与Dubbo整合原理与源码分析:从启动类配置到注解解析

    ServiceBean对象包含了服务的所有参数,如timeout,这些参数可以通过@Service注解进行设置,也可以从应用配置、全局配置或配置中心获取。 服务导出的主要步骤包括: 1. 确定服务参数:整合各个来源的配置,形成最终...

    SpringBoot集成Redisson实现分布式锁的方法示例

    RLock lock(String lockKey, TimeUnit unit, int timeout); boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime); void unlock(String lockKey); void unlock(RLock lock); } ``` ...

    Java-Network-Programming-and-Distributed-Com.rar_java network_ja

    4. **套接字选项**:如SocketOptions,用于配置和获取Socket的属性,例如SO_TIMEOUT用于设置超时。 5. **高级网络API**:如NIO(Non-blocking I/O)和NIO.2,它们提供了一种更有效处理大量连接的方式,特别是对于...

Global site tag (gtag.js) - Google Analytics