TCP通信程序综合练习:实现在线聊天室
4. 综合练习:在线聊天室
声明
该练习程序参考自他人文章,仅用于个人学习,特此声明
文章链接:https://blog.csdn.net/qq_46331050/article/details/118153102
需求:使用TCP的Socket实现一个聊天室
- 服务器端:一个线程专门发送消息,一个线程专门接收消息
- 客户端:一个线程专门发送消息,一个线程专门接收消息
思路
要实现在线聊天室,思路尤为重要
-
首先要保证服务器端只作为中间转发站,他不生产内容,只是把接收内容再发送给另一个客户端。可以先从写[这个程序](###1.1 一个客户收发多条消息)开始入手:
- 一个客户端发送键盘输入内容给服务器端,服务器端接收内容以后既不输出到控制台也不保存到本地文件,而是接着再把这个接收内容发送回发送此信息的客户端
-
下一步就是要实现多个客户收发消息
- [首先](###1.2 多个客户收发多条消息(不使用多线程)),不利用多线程实现多个客户收发消息,缺点是不能有两个及以上客户端同时进行收发操作
- [其次](###1.3 多个客户收发多条消息(多线程)),实现利用多线程实现多个客户同时收发信息
-
基础简易版虽然实现了多个客户同时收发消息的要求,但存在代码复杂不好维护,客户读写没有分开等缺点,下一步就是要实现[oop封装](##2. oop封装版)
-
在线聊天室很明显不能只是自娱自乐用,要实现[群聊功能](##3. 群聊过渡版)
-
实现[私聊功能](##4. 终极版:实现私聊)
1. 基础简易版
1.1 一个客户收发多条消息
- 目标:实现一个客户可以正常收发多条信息
客户端
/**
* 在线聊天室: 客户端
* 目标:实现一个客户可以正常收发(多条)信息
*/
public class MutiClient {
public static void main(String[] args) throws IOException {
System.out.println("-----Client-----");
// 1、建立连接:使用Socket创建客户端 + 服务的地址和端口
Socket client = new Socket("localhost", 1111);
// 2、客户端发送消息
BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); // 对接控制台
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
DataInputStream dis = new DataInputStream(client.getInputStream());
boolean isRunning = true;
while (isRunning) {
String msg = console.readLine();
dos.writeUTF(msg);
dos.flush();
// 3、获取消息
msg = dis.readUTF();
System.out.println(msg);
}
// 4、释放资源
dos.close();
dis.close();
client.close();
}
}
服务器端
/**
* 在线聊天室: 服务器
* 目标:实现一个客户可以正常收发多条消息
* 服务器不生产内容,相当于一个转发站,将客户端的请求转发
*/
public class MutiChat {
public static void main(String[] args) throws IOException {
System.out.println("-----Server-----");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(1111);
// 2、利用Socket的accept方法,监听客户端的请求。阻塞,等待连接的建立
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
DataInputStream dis = new DataInputStream(client.getInputStream());
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
boolean isRunning = true;
while (isRunning) {
// 3、接收消息
String msg = dis.readUTF();
// 4、返回消息
dos.writeUTF(msg);
dos.flush();
}
// 5、释放资源
dos.close();
dis.close();
client.close();
}
}
1.2 多个客户收发多条消息(不使用多线程)
- 目标:实现多个客户可以正常收发多条信息
- 出现排队问题:其他客户必须等待之前的客户退出,才能收发消息
服务器
public class MutiChat {
public static void main(String[] args) throws IOException {
System.out.println("-----Server-----");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(10086);
// 2、利用Socket的accept方法,监听客户端的请求。阻塞,等待连接的建立
while (true) {
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
DataInputStream dis = new DataInputStream(client.getInputStream());
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
boolean isRunning = true;
while (isRunning) {
// 3、接收消息
String msg = dis.readUTF();
// 4、返回消息
dos.writeUTF(msg);
dos.flush();
}
// 5、释放资源
dos.close();
dis.close();
client.close();
}
}
}
1.3 多个客户收发多条消息(多线程)
- 目标:实现多个客户可以正常收发多条信息
- 出现的问题:利用Lambda太复杂,代码过多不好维护;客户端读写没有分开,必须先写后读
服务器代码
public class ThreadMutiChat {
public static void main(String[] args) throws IOException {
System.out.println("-----Server-----");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(10086);
// 2、利用Socket的accept方法,监听客户端的请求。阻塞,等待连接的建立
while (true) {
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
// 加入多线程
new Thread(()->{
DataInputStream dis = null;
DataOutputStream dos = null;
try {
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
boolean isRunning = true;
while (isRunning) {
// 3、接收消息
String msg = null;
try {
msg = dis.readUTF();
// 4、返回消息
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
// e.printStackTrace();
isRunning = false; // 停止线程
}
}
// 5、释放资源
try {
if (null == dos) {
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null == dis) {
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null == client) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
2. oop封装版
目标:封装使用多线程实现多个客户可以正常收发多条消息
-
1、线程代理 Channel,一个客户代表一个 Channel
-
2、实现方法:接收消息 - receive; 发送消息 - send; 释放资源 - release;
-
3、其中释放资源 release方法中利用工具类 MyUtils:实现Closeable接口、可变参数
-
优点:利用封装,代码较为简洁,便于维护
1. 服务器端
/**
* 服务器端,负责接收客户端信息并发送
* 线程代理 Channel,一个客户代表一个 Channel
*/
public class ThreadMutiChat {
public static void main(String[] args) throws IOException {
System.out.println("---服务器开始工作---");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(8888);
// 2、利用Socket的accept方法,监听客户端的请求。阻塞,等待连接的建立
while (true) {
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
new Thread(new Channel(client)).start();
}
}
// 一个客户代表一个Channel
static class Channel implements Runnable {
private DataInputStream dis = null;
private DataOutputStream dos = null;
private Socket client;
private boolean isRunning;
public Channel(Socket client) {
this.client = client;
try {
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
isRunning = true;
} catch (IOException e) {
System.out.println("---构造时出现异常---");
release();
}
}
// 接收消息
private String receive() {
String msg = ""; // 避免空指针
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("---接受消息出现异常---");
release();
}
return msg;
}
// 发送消息
private void send(String msg) {
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
System.out.println("---发送消息出现异常---");
release();
}
}
// 释放资源
private void release() {
this.isRunning = false;
// 封装
MyUtils.close(dis, dos, client);
}
// 线程体
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
send(msg);
}
}
}
}
}
2. 工具类MyUtils
实现Closeable接口,利用可变参数,达到释放资源的作用
示例代码
/**
* 工具类MyUtils:实现Closeable接口,利用可变参数,达到释放资源的作用
*/
public class MyUtils {
public static void close(Closeable... targets) {
// Closeable是IO流中接口,"..."可变参数
// IO流和Socket都实现了Closeable接口,可以直接用
for (Closeable target: targets) {
try {
// 只要是释放资源就要加入空判断
if (null != target) {
target.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
3. 客户端
启用两个线程Send和Receive实现收发信息的分离
示例代码
/**
* 客户端:启用两个线程Send和Receive实现收发信息的分离
*/
public class ThreadMutiClient {
public static void main(String[] args) throws IOException {
System.out.println("-----客户端开始工作-----");
Socket client = new Socket("localhost", 10086);
new Thread(new MySend(client)).start();
new Thread(new MyReceive(client)).start();
}
}
4. 使用多线程封装客户的发送端 – MySend类
实现方法:
- 1、发送消息 - send()
- 2、从控制台获取消息 - getStrFromConsole()
- 3、释放资源 - release()
- 4、线程体 - run()
示例代码
/**
* 使用多线程封装客户的发送端 – MySend类
*
* 实现方法:
* 1、发送消息 - send()
* 2、从控制台获取消息 - getStrFromConsole()
* 3、释放资源 - release()
* 4、线程体 - run()
*/
public class MySend implements Runnable {
private BufferedReader console;
private DataOutputStream dos;
private Socket client;
private boolean isRunning;
public MySend(Socket client) {
this.client = client;
console = new BufferedReader(new InputStreamReader(System.in)); // 对接控制台
try {
dos = new DataOutputStream(client.getOutputStream());
isRunning = true;
} catch (IOException e) {
System.out.println("---客户发送端构造时异常---");
release();
}
}
// 从控制台获取消息
private String getStrFromConsole() {
try {
return console.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
// 发送消息
private void send(String msg) {
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
System.out.println("---客户发送端发送消息异常---");
release();
}
}
@Override
public void run() {
while (isRunning) {
String msg = getStrFromConsole();
if (!msg.equals("")) {
send(msg);
}
}
}
// 释放资源
private void release() {
this.isRunning = false;
MyUtils.close(dos,client);
}
}
5. 使用多线程封装客户的接收端 – MyReceive类
实现方法:
- 1、接收消息 - receive
- 2、释放资源 - release()
- 3、线程体 - run()
示例代码
/**
* 使用多线程封装客户的接收端 – Receive类
* 实现方法:
* 1、接收消息 - send
* 2、释放资源 - release()
* 3、线程体 - run()
*/
public class MyReceive implements Runnable {
private DataInputStream dis;
private Socket client;
private boolean isRunning;
public MyReceive(Socket client) {
this.client = client;
try {
dis = new DataInputStream(client.getInputStream());
isRunning = true;
} catch (IOException e) {
System.out.println("---客户接收端构造时异常---");
release();
}
}
// 接收消息
private String receive() {
String msg = "";
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("---客户接收端接收消息异常---");
release();
}
return msg;
}
// 释放资源
private void release() {
isRunning = false;
MyUtils.close(dis, client);
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
System.out.println(msg);
}
}
}
}
3. 群聊过渡版
目标:加入容器,实现群聊
1. 服务器端
-
1、建立
CopyOnWriteArrayList<Channel>
容器,容器中的元素是Channel客户端代理。要对容器中的元素进行修改的同时实现遍历目的时,推荐使用此容器,避免出问题。 -
2、实现方法
void sendOthers(String msg)
将信息发送给除自己外的其他人。
服务器端实现代码
/**
* 服务器端
*/
public class MyChat {
// 建立 CopyOnWriteArrayList<Channel> 容器
private static CopyOnWriteArrayList<Channel> all = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws IOException {
System.out.println("---服务器开始工作---");
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
Channel c = new Channel(client);
all.add(c); // 管理所有的成员
new Thread(c).start();
}
}
// 一个客户代表一个Channel
static class Channel implements Runnable {
private DataInputStream dis;
private DataOutputStream dos;
private Socket client;
private boolean isRunning;
private String name;
public Channel(Socket client) {
this.client = client;
try {
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
isRunning = true;
// 获取名称
this.name = receive();
// 欢迎
this.send("欢迎你的到来");
sendOthers(this.name + "加入群聊", true);
} catch (IOException e) {
System.out.println("---构造时出现问题---");
release();
}
}
// 接收消息
private String receive() {
String msg = ""; // 避免空指针
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("---接受消息出现问题---");
release();
}
return msg;
}
// 发送消息
private void send(String msg) {
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
System.out.println("---发送消息出现问题---");
release();
}
}
// 群聊:把自己的消息发送给其他人
private void sendOthers(String msg, boolean isSys) {
for (Channel other : all) {
if (other == this) {
continue;
}
if (!isSys) {
other.send(this.name + ": " + msg); // 群聊消息
} else {
other.send("系统消息:" + msg); // 系统消息
}
}
}
// 线程体
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
sendOthers(msg, false);
}
}
}
// 释放资源
private void release() {
this.isRunning = false;
// 封装
Utils.close(dis, dos, client);
// 退出
all.remove(this);
sendOthers(this.name + "离开聊天室", true);
}
}
}
2. 客户端
客户端实现代码
/**
* 客户端
*/
public class MyClient {
public static void main(String[] args) throws IOException {
System.out.println("-----客户端开始工作-----");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Socket client = new Socket("localhost", 8888);
System.out.println("请输入用户名:"); // 不考虑重名
String name = br.readLine();
new Thread(new MySend(client, name)).start();
new Thread(new MyReceive(client)).start();
}
}
3. 客户端Send类实现代码
/**
* 客户端Send类
*/
public class Send implements Runnable {
private BufferedReader console;
private DataOutputStream dos;
private Socket client;
private boolean isRunning;
private String name;
public Send(Socket client, String name) {
this.client = client;
console = new BufferedReader(new InputStreamReader(System.in));
this.isRunning = true;
this.name = name;
try {
dos = new DataOutputStream(client.getOutputStream());
// 发送名称
send(name);
} catch (IOException e) {
System.out.println("Send类构造时异常");
release();
}
}
// 从控制台获取消息
private String getStrFromConsole() {
try {
return console.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
// 发送消息
private void send(String msg) {
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
System.out.println("---客户发送端发送消息异常---");
release();
}
}
@Override
public void run() {
while (isRunning) {
String msg = getStrFromConsole();
if (!msg.equals("")) {
send(msg);
}
}
}
// 释放资源
private void release() {
this.isRunning = false;
MyUtils.close(dos,client);
}
}
4. 客户端Receive类实现代码
/**
* 客户端receive类
*/
public class Receive implements Runnable {
private DataInputStream dis;
private Socket client;
private boolean isRunning;
public Receive(Socket client) {
this.client = client;
try {
dis = new DataInputStream(client.getInputStream());
isRunning = true;
} catch (IOException e) {
System.out.println("---客户接收端构造时异常---");
release();
}
}
// 接收消息
private String receive() {
String msg = "";
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("---客户接收端接收消息异常---");
release();
}
return msg;
}
// 释放资源
private void release() {
isRunning = false;
MyUtils.close(dis, client);
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
System.out.println(msg);
}
}
}
}
5. 工具类
/**
* 工具类MyUtils:实现Closeable接口,利用可变参数,达到释放资源的作用
*/
public class MyUtils {
public static void close(Closeable... targets) {
// Closeable是IO流中接口,"..."可变参数
// IO流和Socket都实现了Closeable接口,可以直接用
for (Closeable target: targets) {
try {
// 只要是释放资源就要加入空判断
if (null != target) {
target.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
4. 终极版:实现私聊
私聊形式:@XXX:
实现方法
1、boolean isPrivate = msg.startsWith("@")
用于判断是否为私聊
-
利用String类中方法
-
boolean startsWith(String prefix)
:测试此字符串是否以指定的前缀开头
2、String targetName = msg.substring(1, index)
用于判断用户名;msg = msg.substring(index+1)
用于判断发送的信息
- 利用String类中方法
substring(int beginIndex)
:返回一个字符串,该字符串是此字符串的子字符串substring(int beginIndex, int endIndex)
:返回一个字符串,该字符串是此字符串的子字符串
1. 服务器端实现代码
/**
* 服务器端
*/
public class MyChat {
private static CopyOnWriteArrayList<Channel> all = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws IOException {
System.out.println("---服务器开始工作---");
ServerSocket server = new ServerSocket(10011);
while (true) {
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
Channel c = new Channel(client);
all.add(c); // 管理所有的成员
new Thread(c).start();
}
}
static class Channel implements Runnable {
private DataInputStream dis;
private DataOutputStream dos;
private Socket client;
private boolean isRunning;
private String name;
public Channel(Socket client) {
this.client = client;
try {
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
isRunning = true;
// 获取名称
this.name = receive();
// 欢迎
this.send("欢迎你的到来");
sendOthers(this.name + "加入群聊", true);
} catch (IOException e) {
System.out.println("---构造时出现问题---");
release();
}
}
private String receive() {
String msg = ""; // 避免空指针
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("---接受消息出现问题---");
release();
}
return msg;
}
private void send(String msg) {
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
System.out.println("---发送消息出现问题---");
release();
}
}
/**
* 群聊:把自己的消息发送给其他人
* 私聊:约定数据格式:@XXX:msg
* @param msg
* @param isSys
*/
private void sendOthers(String msg, boolean isSys) {
boolean isPrivate = msg.startsWith("@");
if (isPrivate) { // 私聊
int index = msg.indexOf(":"); // 第一次冒号出现的位置
// 获取目标和数据
String targetName = msg.substring(1, index);
msg = msg.substring(index+1);
for (Channel other: all) {
if (other.name.equals(targetName)) { // 目标
other.send(this.name + "对您说悄悄话: " + msg); // 群聊消息
}
}
} else {
for (Channel other : all) {
if (other == this) {
continue;
}
if (!isSys) {
other.send(this.name + ": " + msg); // 群聊消息
} else {
other.send("系统消息:" + msg); // 系统消息
}
}
}
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
sendOthers(msg, false);
}
}
}
private void release() {
this.isRunning = false;
MyUtils.close(dis, dos, client);
all.remove(this);
sendOthers(this.name + "离开聊天室", true);
}
}
}
2. 客户端实现代码
/**
* 客户端
*/
public class MyClient1 {
public static void main(String[] args) throws IOException {
System.out.println("-----客户端开始工作-----");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Socket client = new Socket("localhost", 10011);
System.out.println("请输入用户名:"); // 不考虑重名
String name = br.readLine();
new Thread(new MySend(client, name)).start();
new Thread(new MyReceive(client)).start();
}
}
3. 客户端Send类实现代码
/**
* send类
*/
public class MySend implements Runnable {
private BufferedReader console;
private DataOutputStream dos;
private Socket client;
private boolean isRunning;
private String name;
public MySend(Socket client, String name) {
this.client = client;
console = new BufferedReader(new InputStreamReader(System.in));
this.isRunning = true;
this.name = name;
try {
dos = new DataOutputStream(client.getOutputStream());
// 发送名称
send(name);
} catch (IOException e) {
System.out.println("Send类构造时异常");
release();
}
}
private String getStrFromConsole() {
try {
return console.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
private void send(String msg) {
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
System.out.println("---客户发送端发送消息异常---");
release();
}
}
@Override
public void run() {
while (isRunning) {
String msg = getStrFromConsole();
if (!msg.equals("")) {
send(msg);
}
}
}
private void release() {
this.isRunning = false;
MyUtils.close(dos,client);
}
}
4. 客户端receive类实现代码
/**
* receive类
*/
public class MyReceive implements Runnable {
private DataInputStream dis;
private Socket client;
private boolean isRunning;
public MyReceive(Socket client) {
this.client = client;
try {
dis = new DataInputStream(client.getInputStream());
isRunning = true;
} catch (IOException e) {
System.out.println("---客户接收端构造时异常---");
release();
}
}
private String receive() {
String msg = "";
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("---客户接收端接收消息异常---");
release();
}
return msg;
}
private void release() {
isRunning = false;
MyUtils.close(dis, client);
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
System.out.println(msg);
}
}
}
}
5. 工具类实现代码
/**
* 工具类
*/
public class MyUtils {
public static void close(Closeable... targets) {
for (Closeable target: targets) {
try {
if (null != target) {
target.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
代码测试
练习总结
服务器端思路
main方法
- 创建服务器端套接字
- 循环体
- 接收信息,返回一个Socket对象client
- 创建多线程,将所有建立连接关系的客户端套接字添加到数组all进行统一管理
sendOthers方法
- 通过客户端发送信息是否以@开头来判断是否是私聊信息
boolean isPrivate = msg.startsWith("@");
- 如果是私聊信息,就用判断框语句进行处理
- 定位该私聊信息中 ":" 第一次出现的位置为index,从而锁定冒号之前的私聊对象和冒号之后的私聊内容
int index = msg.indexOf(":");//定位私聊信息中第一个:出现的位置
String targetName = msg.substring(1, index);//将发送的私聊信息数组从第1位(@为第0位)到第index位(:)之前的内容定义为私聊对象的名称targetName
因为数组范围是左闭右开的,所以事实上第index位也就是信息中出现的第一个冒号是不包括在私聊对象名的信息之内的
- 同样的道理,分析以下代码
for (Channel other: all) {
if (other.name.equals(targetName)) { // 目标
other.send(this.name + "对您说悄悄话: " + msg); // 群聊消息
}
}
-
Channel other : all
-
- 意为遍历整个all数组中的每一个元素,遍历到的单个元素返回给other
- 上边这句话有点绕,其实意思就是现在的other就是被遍历出来的单个元素了,因为自己写的send方法是属于每一个客户端的而不是属于整个包含所有客户端套接字的数组的,所以要用将数组中的单个元素"剥离出来",然后用other.send去调用send方法。
- 其实就是之前已经把所有客户端套接字添加进数组了,这一步是在遍历的同时把遍历到的每一个客户端套接字再分出来,返回给"other"
- 如下图所示,很明显是不能用整个数组去调用send方法的
-
以上代码意为遍历信道数组中的其他元素(其他客户端套接字)
-
-
经测试发现上一行的说法是错误的,应该是遍历数组的全部元素也就是所有客户端套接字
-
另外如下图所示,很明显,客户端是可以给自己发送所谓的私聊,这一点还需要改进
-
如果有某一个客户端套接字名称和私聊对象名是一样的,就把以下信息发送给该对象名客户端,如上图所示
this.name + "对您说悄悄话: " + msg
-
如果客户端发送的信息不是私聊信息,发送信息给除"自己"以外的其他客户端套接字,代码和步骤如下
else { for (Channel other : all) { if (other == this) { continue; } if (!isSys) { other.send(this.name + ": " + msg); // 群聊消息 } else { other.send("系统消息:" + msg); // 系统消息 } } }
- 1、判断遍历到的客户端套接字元素是不是自己(this),如果是,忽略该客户端套接字,continue 向下继续执行
- 2、判断是否是系统信息。
run重写方法
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
sendOthers(msg, false);
}
}
}
如果发送信息不为空(之所以用 "" 而不用null是为了避免空指针),调用sendOthers方法
release方法
private void release() {
this.isRunning = false;
MyUtils.close(dis, dos, client);
all.remove(this);
sendOthers(this.name + "离开聊天室", true);
}
当当前客户端结束运行
- 用工具类关闭该客户端套接字及dis dos数据
- 在all数组中将该客户端套接字移除
- 由服务器端向其他客户端套接字发送信息
this.name + "离开聊天室", true
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律