一、核心代码分析说明
(1)Sever类——connect()方法:在建立与客户端的连接后,首先需要开启多线程,主线程是显示界面,新开的线程是对数据的处理,包括对客户信息的存储以及对客户发送过来信息的处理。
public static void connect() {
try (ServerSocket server = new ServerSocket(PORT)) {
while (true) {
try {
Socket connection = server.accept();
new Thread() {// 多线程
@Override
public void run() {
String client_mes = connection.getInetAddress().getHostName() + ":" + connection.getPort();
clientMap.put(client_mes, connection);// 把客户信息用hashMap存储起来 方便查找
item[count++] = client_mes;// 连接上的客户端的列表
String[] items = new String[count];
for (int k = 0; k < count; k++)
items[k] = item[k];
list.setListData(items);// 把列表放入组件中显示
lblNewLabel_1.setText(count + " client connect");// 更改界面中连接的客户数量
mes_receive(connection, client_mes);// 对客户发送过来信息的处理
}
}.start();
} catch (IOException ex) {
}
}
} catch (Exception ex) {
System.out.println("connect error");
System.err.println(ex);
}
}
(2)Sever类——mes_receive()方法:用一个while来不断的判断发送过来的信息是属于哪一类的,是talk、login、还是logout的,根据此进行不同的操作。
while (true) {
request = buffer_reader.readLine();
System.out.println("request: " + request + "\n");
if (request.startsWith("talk")) {
request = request.substring(4);
receive_mes_textArea.append(client_mes + " : " + request + "\n");
} else if (request.startsWith("logout")) {// 客户端退出登录
System.out.println("clients: " + clients);
request = request.substring(6);
clients = request;
clientMap.remove(clients);
for (int k = 0; k < count; k++) {
if (item[k].equals(clients)) {
for (int j = k; j < count; j++)
item[j] = item[j + 1];
item[count] = null;
count--;
System.out.println("count0: " + count);
break;
}
}
// for(String s:item)
// System.out.pri