界面如下:
----------
項目目錄結構
代碼:
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>