Java心跳消息的实现,hadoop的rpc基础(心跳篇)下一篇(rpc通信篇)

像现在的大型开源项目的源码,真的很值得认真的分析分析

心跳机制在hadoop的中占了非常重要的地位,现在我们就来简单的勾画一下心跳检测

(1)

客户端

public static void main(String[] args) {
		int port = 9999;
		Socket client = null;
		String ip = "127.0.0.1";
		int cout = 0 ;
		
		// 构造客户端socket对象
		try {

			client = new Socket(ip, port);
			OutputStream out = client.getOutputStream();
			System.out.println("客户端2启动");
			while(true)
			{
				cout++;
				
				Thread.sleep(5000);
				out.write(String.valueOf(cout).getBytes());
				
			}
			System.out.println("客户端2退出");
		} catch (Exception e) {
			e.printStackTrace();

		}
		finally
		{
			System.out.println("退出");
		}
	}

(2)

服务器端

public static void main(String[] args) {
		
		try {
			ServerSocket server = new ServerSocket(9999);
			while(true)
			{
				//接受客户机的连接请求
				Socket client = server.accept();
				new TestServer(client).start();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	static class TestServer extends Thread
	{

		Socket client  = null ;
		
		public TestServer(){
			
		}
		
		public TestServer(Socket client)
		{
			this.client = client ;
		}
		
		@Override
		public void run() {
			
			try
			{
				InputStream is = this.client.getInputStream();
				while(true)
				{
					if (this.client.isClosed()
							|| this.client.isConnected() == false)
						break;
	
					try {
						System.out.println(Thread.currentThread().getName()+"=>"+"心跳测试正常!");
					} catch (Exception ex) {
						System.out.println(Thread.currentThread().getName()+"=>"+"心跳测试异常!");
						break;
					}
					byte []data =  new byte[28];
					is.read(data);
					System.out.println(Thread.currentThread().getName()+"=>"+new String(data));
				}
			}
			catch(Exception e)
			{
				System.out.println(e.toString());
			}
			finally
			{
				System.out.println(Thread.currentThread().getName()+"=>"+"客户端关闭");
			}
		}
		
	}

通过简单的例子 是不是已经知道心跳消息的实现了


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值