Java实现在线聊天室(层层递进)
作者:imByte 发布时间:2022-06-13 11:03:47
本文实例为大家分享了Java实现在线聊天室的具体代码,供大家参考,具体内容如下
- 本文讲述了从实现单个多个客户的收发信息(基础简易版),到各种实现代码的封装(oop版),实现群聊(群聊过渡版),到最后实现私聊(终极版)的过程
- 本文内容是在初步学习网络编程时,练习强化记忆时的学习总结
- 主要利用了TCP网络编程和多线程
- 如有问题,欢迎指出
综合案例:在线聊天室
需求:使用TCP的Socket实现一个聊天室
服务器端:一个线程专门发送消息,一个线程专门接收消息
客户端:一个线程专门发送消息,一个线程专门接收消息
1. 基础简易版
1.1 一个客户收发多条消息
目标:实现一个客户可以正常收发多条信息
服务器
/**
* 在线聊天室: 服务器
* 目标:实现一个客户可以正常收发多条消息
* 服务器不生产内容,相当于一个转发站,将客户端的请求转发
*/
public class MutiChat {
public static void main(String[] args) throws IOException {
System.out.println("-----Server-----");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(8888);
// 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();
}
}
客户端
/**
* 在线聊天室: 客户端
* 目标:实现一个客户可以正常收发(多条)信息
*/
public class MutiClient {
public static void main(String[] args) throws IOException {
System.out.println("-----Client-----");
// 1、建立连接:使用Socket创建客户端 + 服务的地址和端口
Socket client = new Socket("localhost", 8888);
// 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();
}
}
1.2 多个客户收发多条消息(不使用多线程)
目标:实现多个客户可以正常收发多条信息
出现排队问题:其他客户必须等待之前的客户退出,才能收发消息
服务器
public class MutiChat {
public static void main(String[] args) throws IOException {
System.out.println("-----Server-----");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(8888);
// 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(8888);
// 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方法中利用工具类 Utils:实现Closeable接口、可变参数
好处:利用封装,是代码简洁,便于维护
服务器端
示例代码:
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;
// 封装
Utils.close(dis, dos, client);
}
// 线程体
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
send(msg);
}
}
}
}
}
工具类Utils:实现Closeable接口,利用可变参数,达到释放资源的作用
示例代码
public class Utils {
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();
}
}
}
}
客户端:启用两个线程Send和Receive实现收发信息的分离
示例代码
public class ThreadMutiClient {
public static void main(String[] args) throws IOException {
System.out.println("-----客户端开始工作-----");
Socket client = new Socket("localhost", 8888);
new Thread(new Send(client)).start();
new Thread(new Receive(client)).start();
}
}
使用多线程封装客户的发送端 – Send类
实现方法:
1、发送消息 - send()
2、从控制台获取消息 - getStrFromConsole()
3、释放资源 - release()
4、线程体 - run()
示例代码
public class Send implements Runnable {
private BufferedReader console;
private DataOutputStream dos;
private Socket client;
private boolean isRunning;
public Send(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;
Utils.close(dos,client);
}
}
使用多线程封装客户的接收端 – Receive类
实现方法:
1、接收消息 - send
2、释放资源 - release()
3、线程体 - run()
示例代码
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;
Utils.close(dis, client);
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
System.out.println(msg);
}
}
}
}
3. 群聊过渡版
目标:加入容器,实现群聊
服务器端
1、建立 CopyOnWriteArrayList<Channel> 容器,容器中的元素是Channel客户端代理。要对元素进行修改同时遍历时,推荐使用此容器,避免出问题。
2、实现方法void sendOthers(String msg)将信息发送给除自己外的其他人。
服务器端实现代码
public class Chat {
// 建立 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);
}
}
}
客户端实现代码
public class Client {
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 Send(client, name)).start();
new Thread(new Receive(client)).start();
}
}
客户端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;
Utils.close(dos,client);
}
}
客户端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;
Utils.close(dis, client);
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
System.out.println(msg);
}
}
}
}
运行结果
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):
返回一个字符串,该字符串是此字符串的子字符串
服务器端实现代码
public class Chat {
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();
}
}
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;
Utils.close(dis, dos, client);
all.remove(this);
sendOthers(this.name + "离开聊天室", true);
}
}
}
客户端实现代码
public class Client {
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 Send(client, name)).start();
new Thread(new Receive(client)).start();
}
}
客户端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;
Utils.close(dos,client);
}
}
客户端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;
Utils.close(dis, client);
}
@Override
public void run() {
while (isRunning) {
String msg = receive();
if (!msg.equals("")) {
System.out.println(msg);
}
}
}
}
Utils类实现代码
public class Utils {
public static void close(Closeable... targets) {
for (Closeable target: targets) {
try {
if (null != target) {
target.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
输出结果
来源:https://blog.csdn.net/qq_46331050/article/details/118153102


猜你喜欢
- 本文实例为大家分享了java实现文件上传下载的具体代码,供大家参考,具体内容如下1.上传单个文件Controller控制层import ja
- springmvc控制登录用户session失效后跳转登录页面,废话不多少了,具体如下:第一步,配置 web.xml <session
- 一、LinkedHashMap的类继承关系二、源码分析1.自己对LinkedHashMap的理解从继承关系上,我们看到LinkedHashM
- 该着色方法一句着色图层中要素类的某个数值字段的属性值,按这个属性值为每种不同值得要素单独分配一种显示符号样式。关键在于获取该字段所有要素的唯
- 1.常用属性Name:名称;BackColor:设置控件背景颜色;Enabled:是否可用;FlayStyle:控件样式;Image:设置控
- execution (常用,方法级别的匹配)语法:execution(modifiers-pattern? ret-type-pattern
- C/C++ 左移<<, 右移>>作用1. 左移 <<取两个数字,左移第一个操作数的位,第二个操作数决定要
- 从相册或拍照更换图片功能的实现:(取图无裁剪功能)获取图片方式: (类似更换头像的效果)1、手机拍照 选择图片;2、相册选取图片;本文只是简
- Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中。然而 XML 配置文件需要通过 D
- Java事件处理机制java中的事件机制的参与者有3种角色:1.event object:事件状态对象,用于listener的相应的方法之中
- MyBatis全局配置文件MyBatis 的配置文件包含了影响 MyBatis 行为甚深的设置(settings)和属性(propertie
- 本文介绍了如何使用 C# 实现一个简化 Scheme——iScheme 及其解释器。如果你对下面的内容感兴趣:实现基本的词法分析,语法分析并
- JVM(Java虚拟机)是一个抽象的计算模型。就如同一台真实的机器,它有自己的指令集和执行引擎,可以在运行时操控内存区域。目的是为构建在其上
- 介绍Spring Profiles 提供了一套隔离应用配置的方式,不同的 profiles 提供不同组合的配置,在不同的环境中,应用在启动时
- 开窗函数能在每行的最后一行都显示聚合函数的结果,所以聚合函数可以用作开窗函数聚合函数和开窗函数聚合函数是将多行变成一行,如果要显示其他列,必
- java String的深入理解一、Java内存模型 按照官方的说法:Java 虚拟机具有一个堆,堆是运行时数据区域,所有类实例和
- 主要区别在于是否延迟加载。load方法不会立即访问数据库,当试图加载的记录不存在时,load方法返回一个未初始化的代理对象。get方法总是立
- 目的了解ReentrantLock获取锁、释放锁的流程代码package com.company.aqs;import java.util.
- Redis模糊匹配批量删除操作,使用RedisTemplate操作: public void deleteByPrex(String pre
- 本文实例讲述了Android中ListView下拉刷新的实现方法。分享给大家供大家参考,具体如下:ListView中的下拉刷新是非常常见的,