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()+"=>"+"客户端关闭");
			}
		}
		
	}

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


你可能感兴趣的:(hadoop,心跳消息)