因为要做一个医疗项目,考虑到患者在挂号前需要有一个在线问诊功能,所以从CSDN上找了一篇博客(大佬ID:西瓜不甜柠檬不酸)并且实现了,为了代码不丢失,在这里记录一下:
首先是后台代码:
Pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.boai</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
在这里要引入一个WebSocket的启动依赖和Gson的依赖,Gson的作用是转化字符串为json,WebSocket的作用是内部封装了Http和TCP通讯协议,所以这两个架包是必须导入的
再创建一个工具类WebSocketConfig,代码如下:
package com.boai.utils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @ClassName WebSocketConfig
* @Author 王弈程
* @Date 2021/9/21 14:09
**/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
再创建一个实体类SocketMsg,代码如下:
package com.boai.model;
import lombok.Data;
/**
* @ClassName SocketMsg
* @Author 王弈程
* @Date 2021/9/21 14:10
**/
@Data
public class SocketMsg {
private int type; //聊天类型0:群聊,1:单聊.
private String fromUser;//发送者.
private String toUser;//接受者.
private String msg;//消息
}
再创一个业务层WebSocketService,代码如下:
package com.boai.service;
import com.boai.model.SocketMsg;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @ClassName WebSocketService
* @Author 王弈程
* @Date 2021/9/21 14:12
**/
@ServerEndpoint(value = "/websocket/{nickname}")
@Component
public class WebSocketService {
private String nickname;
private Session session;
//用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
//用来记录sessionId和该session进行绑定
private static Map<String, Session> map = new HashMap<String, Session>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("nickname") String nickname) {
Map<String,Object> message=new HashMap<String, Object>();
this.session = session;
this.nickname = nickname;
map.put(session.getId(), session);
webSocketSet.add(this);//加入set中
System.out.println("有新连接加入:" + nickname + ",当前在线人数为" + webSocketSet.size());
//this.session.getAsyncRemote().sendText("恭喜" + nickname + "成功连接上WebSocket(其频道号:" + session.getId() + ")-->当前在线人数为:" + webSocketSet.size());
message.put("type",0); //消息类型,0-连接成功,1-用户消息
message.put("people",webSocketSet.size()); //在线人数
message.put("name",nickname); //昵称
message.put("aisle",session.getId()); //频道号
this.session.getAsyncRemote().sendText(new Gson().toJson(message));
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
System.out.println("有一连接关闭!当前在线人数为" + webSocketSet.size());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session, @PathParam("nickname") String nickname) {
System.out.println("来自客户端的消息-->" + nickname + ": " + message);
//从客户端传过来的数据是json数据,所以这里使用jackson进行转换为SocketMsg对象,
// 然后通过socketMsg的type进行判断是单聊还是群聊,进行相应的处理:
ObjectMapper objectMapper = new ObjectMapper();
SocketMsg socketMsg;
try {
socketMsg = objectMapper.readValue(message, SocketMsg.class);
if (socketMsg.getType() == 1) {
//单聊.需要找到发送者和接受者.
socketMsg.setFromUser(session.getId());//发送者.
Session fromSession = map.get(socketMsg.getFromUser());
Session toSession = map.get(socketMsg.getToUser());
//发送给接受者.
if (toSession != null) {
//发送给发送者.
Map<String,Object> m=new HashMap<String, Object>();
m.put("type",1);
m.put("name",nickname);
m.put("msg",socketMsg.getMsg());
fromSession.getAsyncRemote().sendText(new Gson().toJson(m));
toSession.getAsyncRemote().sendText(new Gson().toJson(m));
} else {
//发送给发送者.
fromSession.getAsyncRemote().sendText("系统消息:对方不在线或者您输入的频道号不对");
}
} else {
//群发消息
broadcast(nickname + ": " + socketMsg.getMsg());
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 群发自定义消息
*/
public void broadcast(String message) {
for (WebSocketService item : webSocketSet) {
item.session.getAsyncRemote().sendText(message);//异步发送消息.
}
}
}
注意:@ServerEndpoint(value = "/websocket/{nickname}")的作用是确定方位路径,在前端能通过这个路径直接访问该方法
接下来就是前段代码,前端我使用了ElementUI配合Vue进行使用,所以需要先下载一下ElementUI,并且全局引用,我这里使用的是Vue3.0
前端代码如下:
<template>
<div>
<el-row :gutter="20">
<el-col :span="12" :offset="6">
<div class="main">
<el-row>
<el-input
placeholder="请输入自己的昵称"
prefix-icon="el-icon-user-solid"
v-model="name"
style="width:50%"
></el-input>
<el-button type="primary" @click="conectWebSocket()">建立连接</el-button>
<el-button type="danger">断开连接</el-button>
</el-row>
<el-row>
<el-input
placeholder="请输入对方频道号"
prefix-icon="el-icon-phone"
v-model="aisle"
style="width:40%"
></el-input>
</el-row>
<el-row>
<el-input
placeholder="请输入要发送的消息"
prefix-icon="el-icon-s-promotion"
v-model="messageValue"
style="width:50%"
></el-input>
<el-button type="primary" @click="sendMessage()">发送</el-button>
</el-row>
<div class="message">
<div v-for="(value,key,index) in messageList" :key="index">
<el-tag v-if="value.name==name" type="success" style="float:right">我:{
{value.msg}}</el-tag>
<br />
<el-tag v-if="value.name!=name" style="float:left">{
{value.name}}:{
{value.msg}}</el-tag>
<br />
</div>
</div>
</div>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
data() {
return {
name: "", // 昵称
websocket: null, // WebSocket对象
aisle: "", // 对方频道号
messageList: [], // 消息列表
messageValue: "" // 消息内容
};
},
methods: {
conectWebSocket: function() {
console.log("建立连接");
if (this.name === "") {
this.$alert("请输入自己的昵称", "提示", {
confirmButtonText: "确定",
callback: action => {}
});
} else {
//判断当前浏览器是否支持WebSocket
if ("WebSocket" in window) {
this.websocket = new WebSocket(
"ws://localhost:8080/websocket/" + this.name
);
} else {
alert("不支持建立socket连接");
}
//连接发生错误的回调方法
this.websocket.onerror = function() {
};
//连接成功建立的回调方法
this.websocket.onopen = function(event) {
};
//接收到消息的回调方法
var that = this;
this.websocket.onmessage = function(event) {
var object = eval("(" + event.data + ")");
console.log(object);
if (object.type == 0) {
// 提示连接成功
console.log("连接成功");
that.showInfo(object.people, object.aisle);
}
if (object.type == 1) {
//显示消息
console.log("接受消息");
that.messageList.push(object);
}
};
//连接关闭的回调方法
this.websocket.onclose = function() {};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
this.websocket.close();
};
}
},
// 发送消息
sendMessage: function() {
var socketMsg = { msg: this.messageValue, toUser: this.aisle };
if (this.aisle == "") {
//群聊.
socketMsg.type = 0;
} else {
//单聊.
socketMsg.type = 1;
}
this.websocket.send(JSON.stringify(socketMsg));
},
showInfo: function(people, aisle) {
this.$notify({
title: "当前在线人数:" + people,
message: "您的频道号:" + aisle,
duration: 0
});
}
}
};
</script>
<style scoped>
.main {
position: relative;
top: 20px;
}
.message {
position: relative;
overflow:auto;
top: 20px;
width: 100%;
height: 400px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
padding: 5px;
}
</style>
注意: this.websocket = new WebSocket("ws://localhost:8080/websocket/" + this.name);
以后端口有所更改,直接把8080改为你的端口即可
下面我来演示一下流程
首先打开两个页面,一个模拟为患者,另一个则是医生,输入完成后,点击连接,则生成了自己的频道号
分别输入对方的频道号,然后输入你想输入的内容,即可模仿在线聊天,但要注意的是,必须在同一个局域网内
今天的文章SpringBoot+Vue+ElementUI实现客服聊天分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/40098.html