界面如下:
----------
项目目录结构
代码:
https://gitee.com/kunlunsoft/inetAdress_socket.git
d代码核心注意事项:
1.服务器socket 对客户端socket的监听应该放在线程中,否则界面会阻塞,"死机";
new Thread(new Runnable() {
@Override
public void run() {
try {
client = server.accept();
System.out.println("有客户端连接成功 :" + client.getLocalAddress().getHostAddress());
ServerApp.isConnected = true;
reader = new BufferedReader(new InputStreamReader(
client.getInputStream()));
out = new PrintStream(client.getOutputStream());
out.println(Constant2.CRLF_newLine_placeholder + "connect successfully");
} catch (IOException e) {
e.printStackTrace();
System.out.println("error");
return;
}
}
}).start();
2.通过socket读取聊天信息时要使用两重循环
第一次(最外层)循环是死循环,目的是持续监听socket输入流,判断是否有聊天信息;
第二层循环 是用于读取socket,如果没有可读取的内容,则会退出该循环.
3,如果连续两次循环都没有读取到内容,则说明socket连接异常断开了
代码:
https://gitee.com/kunlunsoft/inetAdress_socket.git
netty版本的简易聊天工具:
依赖:
<!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.21.Final</version> </dependency>