2016-7-30 网络通信原理
网络通信原理:
package com.example; import java.util.ArrayList; import java.util.Date; import java.util.List; // 回调接口 interface ICallback { String getString(); void fun(String str); } // 登录 class A implements ICallback { String string = "login"; public String getString() { return string; } @Override public void fun(String str) { System.out.println(string + " : " + str); } } // 回调的核心 class B { List<ICallback> iList = new ArrayList<>(); // 注册被回调(注册函数) public void addTo(ICallback iCallback) { iList.add(iCallback); } // 回调函数 public void excute() { int num = 0; for (ICallback i : iList) { i.fun(String.valueOf(num++)); } } } // p2p聊天 class C implements ICallback { String string = "p2p"; @Override public String getString() { return string; } @Override public void fun(String str) { System.out.println(string + " : " + str); } } // 群聊 class D implements ICallback { String string = "chatroom"; @Override public String getString() { return string; } @Override public void fun(String str) { System.out.println(string + " : " + str); } } // 视频 class F implements ICallback { String string = "camera chat"; @Override public String getString() { return string; } @Override public void fun(String str) { System.out.println(string + " : " + str); } } // QQ电话 class G implements ICallback { String string = "QQ phone"; @Override public String getString() { return string; } @Override public void fun(String str) { System.out.println(string + " : " + str); } } class X extends Thread { boolean isRunning = true; int i = 1; public static int num = 0; List<ICallback> iList = new ArrayList<>(); // 注册函数 : 注册被回调类方法 public void addTo(ICallback iCallback) { iList.add(iCallback); } // 回调函数 : 处理回调 public void run() { super.run(); while (isRunning) { num++; try { System.out.println("=====" + new Date(System.currentTimeMillis()) + "====="); System.out.println("[num] = " + num + " | get a message!"); System.out.println("---------"); Thread.sleep(2000); // 处理所有回调 for (ICallback i : iList) { i.fun("<-[message]"); } System.out.println("======================================"); // 模拟现实,每隔一段时间就移除一个回调(监听) if (num == 2 * i) { Thread.sleep(2000); System.out.println("+++++++++++++"); System.out.println(iList.get(0).getString() +" completed !"); System.out.println("+++++++++++++"); removeFrom(0); i++; Thread.sleep(2000); } Thread.sleep(7000); if (iList.isEmpty()) { System.out.println("**************************"); System.out.println("Do not have a active action"); isRunning = false; } } catch (InterruptedException e) { e.printStackTrace(); } } } public void sstart() { start(); } public void removeFrom(int i) { iList.remove(i); } } public class MyClass { public static void main(String[] args) { X x = new X(); // 动态挂接被回调的类函数 x.addTo(new A()); x.addTo(new C()); x.addTo(new D()); x.addTo(new F()); x.addTo(new G()); x.sstart(); } }