就是一个 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
用 lightcomm4j 写一个简单的聊天室吧!
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();
}
}
}
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();
}
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.