V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
luohaha
V2EX  ›  分享创造

分享一个轻量 Java 异步网络通信库 LightComm4J

  •  
  •   luohaha · 2017-05-07 15:54:42 +08:00 · 3364 次点击
    这是一个创建于 2545 天前的主题,其中的信息可能已经有所发展或是发生改变。

    介绍

    就是一个 java 的异步网络通信库。上手简单。

    地址

    https://github.com/luohaha/LightComm4J

    下载与安装

    Maven

    <dependency>
      <groupId>com.github.luohaha</groupId>
      <artifactId>LightComm4J</artifactId>
      <version>0.0.4-SNAPSHOT</version>
    </dependency>
    

    Download jar

    download

    例子

    用 lightcomm4j 写一个简单的聊天室吧!

    • server-side
    public class ChatRoomServer {
    	public static void main(String[] args) {
    		ServerParam param = new ServerParam("localhost", 8888);
    		Set<Conn> conns = new HashSet<>();
    		param.setBacklog(128);
    // 注册 accept 事件回调
    		param.setOnAccept(conn -> {
    			try {
    				String m = conn.getRemoteAddress().toString() + " " + "is online!";
    				conns.add(conn);
    				conns.forEach(c -> {
    					try {
    						c.write(m.getBytes());
    					} catch (Exception e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				});
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		});
    // 注册 read 事件回调
    		param.setOnRead((conn, msg) -> {
    			try {
    				String m = conn.getRemoteAddress().toString() + " : " + new String(msg);
    				conns.forEach(c -> {
    					try {
    						c.write(m.getBytes());
    					} catch (Exception e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				});
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		});
    // 注册 close 事件回调
    		param.setOnClose(conn -> {
    			try {
    				conns.remove(conn);
    				String m = conn.getRemoteAddress().toString() + " " + "is offline!";
    				conns.forEach(c -> {
    					try {
    						c.write(m.getBytes());
    					} catch (Exception e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				});
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		});
    // 注册异常事件回调
    		param.setOnReadError((conn, err) -> {
    			System.out.println(err.getMessage());
    		});
    		param.setOnWriteError((conn, err) -> {
    			System.out.println(err.getMessage());
    		});
    		param.setOnAcceptError(err -> {
    			System.out.println(err.getMessage());
    		});
    		
    		LightCommServer server = new LightCommServer(param, 4);
    		try {
    			server.start();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    
    
    • client-side
    public class ChatRoomClient {
    	public static void main(String[] args) {
    		ClientParam param = new ClientParam();
    // 注册 connect 事件回调
    		param.setOnConnection(conn -> {
    			new Thread(() -> {
    				Scanner scanner = new Scanner(System.in);
    				while (scanner.hasNext()) {
    					String msg = scanner.nextLine();
    					try {
    						conn.write(msg.getBytes());
    					} catch (Exception e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				}
    			}).start();
    		});
    // 注册 read 事件回调
    		param.setOnRead((conn, msg) -> {
    			System.out.println("[chatroom] " + new String(msg));
    		});
    // 注册 close 事件回调
    		param.setOnClose(conn -> {
    			System.out.println("[chatroom] " + "chatroom close!");
    		});
    		try {
    			LightCommClient client = new LightCommClient(4);
    			client.connect("localhost", 8888, param);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    
    
    8 条回复    2017-05-14 20:28:08 +08:00
    WhoMercy
        1
    WhoMercy  
       2017-05-07 22:04:58 +08:00 via Android
    战略性 mark
    java8 让代码简化了不少,不过看起来真不大习惯😅
    letitbesqzr
        2
    letitbesqzr  
       2017-05-07 22:11:05 +08:00
    @WhoMercy 现在感觉不敢直视各种循环非 java8 的代码了
    luohaha
        3
    luohaha  
    OP
       2017-05-07 22:23:59 +08:00
    @WhoMercy 对啊,java8 各种语法糖太好用了,希望以后糖能更多谢~~
    luohaha
        4
    luohaha  
    OP
       2017-05-07 22:24:12 +08:00
    @letitbesqzr 😄哈哈
    yidinghe
        5
    yidinghe  
       2017-05-11 21:10:23 +08:00
    看了一下代码,问题有一些:

    * 首先是没有使用任何日志框架,输出全部都是用 `System.out`;
    * 其次对异常的处理显得比较随意,没有整体规划,一些空 catch 块没有注释说明;
    * 再就是到处都遗留了 Eclipse 缺省的 TODO 行,这是留着干嘛呢;
    * 还有正式代码中包含了测试用的 main() 方法,最好还是改成单元测试。

    还有举个例子:

    ```
    // IoWorker.java
    if (param == null)
    System.out.println(">>>>>>>>>>>>>>>");
    if (param.getOnRead() != null) {
    ops |= SelectionKey.OP_READ;
    }
    ```

    第一行判断 param 是否为 null。如果这个条件为 true,是不是就应该直接 return 了,至少也应该避免执行到第三行,因为这里此时一定会抛出空指针异常。

    总之我觉得这个项目显然在楼主自己这里还缺乏足够的实际应用。
    luohaha
        6
    luohaha  
    OP
       2017-05-12 10:56:06 +08:00
    @yidinghe 多谢建议啊,确实啊,这个项目只是刚开始还有很多细节和具体的工作还没有做啊,比如日志和异常处理这两块。。再次感谢您的意见!
    woshixiaohao1982
        7
    woshixiaohao1982  
       2017-05-14 20:24:33 +08:00
    回调地狱..
    woshixiaohao1982
        8
    woshixiaohao1982  
       2017-05-14 20:28:08 +08:00
    说实话,我个人还是倾向于 用代码来维护状态,,事件回调 真的很蛋疼
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5282 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 08:20 · PVG 16:20 · LAX 01:20 · JFK 04:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.