零、小谈websocket实现聊天室的群发功能和单聊功能
一、实现效果
本文使用springBoot+websocket实现了一个可支持群发和单聊功能的聊天室。场景有两个
①A,B,C三人在线,A发公共消息。所有人都能看到
②A,B,C三人在线,A发给B私聊消息。只有A和B能看到消息,C看不到消息
二、上代码
1、pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、websocket配置文件
路径 com.guosh.longze.config. WebSocketConfig
package com.guosh.longze.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig{
/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、model对象
路径:com.guosh.longze.model. SocketMsg
package com.guosh.longze.model;
/**
* @Auther: fengqx
* @Date: 2021/11/20 - 11 -20 - 10:52
* @Description: com.guosh.longze.model
* @Version: 1.0
*/
public class SocketMsg {
//聊天类型0:群聊,1:单聊
private int type;
//发送者
private String fromUser;
//接受者
private String toUser;
//消息
private String msg;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getFromUser() {
return fromUser;
}
public void setFromUser(String fromUser) {
this.fromUser = fromUser;
}
public String getToUser() {
return toUser;
}
public void setToUser(String toUser) {
this.toUser = toUser;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
4、MyWebSocket socket接口文件
package com.guosh.longze.controller;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guosh.longze.model.SocketMsg;
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;
/**
* @Auther: fengqx 实现简单kafka+websocket打通,仅仅展示消息
* @Date: 2021/11/14 - 11 -14 - 21:06
* @Description: com.guosh.longze.service
* @Version: 1.0
*/
@Component
@ServerEndpoint(value = "/myWebsocket/{nickname}")
public class MyWebSocket {
//用来存放每个客户端对应的MyWebSocket对象。
//
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String nickname;
//用来记录sessionId和该session进行绑定
private static Map<String,Session> map = new HashMap<String, Session>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("nickname") String nickname) {
this.session = session;
this.nickname=nickname;//保存昵称
map.put(session.getId(),session);
webSocketSet.add(this); //加入到websocket中
//加入set中
System.out.println("有新连接加入:"+nickname+"!当前在线人数为"+ webSocketSet.size());
this.session.getAsyncRemote().sendText("恭喜"+nickname+"成功连接上WebSocket(其频道号:"+session.getId()+")-->当前在线人数为:"+webSocketSet.size());
}
/**
* 连接关闭调用的方法
*/
@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){
//发送给发送者.
fromSession.getAsyncRemote().sendText(nickname+":"+socketMsg.getMsg());
toSession.getAsyncRemote().sendText(nickname+":"+socketMsg.getMsg());
}else{
//发送给发送者.
fromSession.getAsyncRemote().sendText("系统消息:对方不在线或者您输入的频道号不对");
}
}else{
//群发消息
broadcast(nickname+": "+socketMsg.getMsg());
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// //群发消息
// broadcast(nickname+": "+message);
}
/**
* 发生错误时调用
*/
@OnError
public void one rror(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 群发自定义消息
*/
public void broadcast(String message) throws IOException {
for (MyWebSocket item : webSocketSet) {
//同步异步说明参考:http://blog.csdn.net/who_is_xiaoming/article/details/53287691
//同步发送消息
//this.session.getBasicRemote().sendText(message);
//异步发送消息
item.session.getAsyncRemote().sendText(message);
//异步发送消息.
}
}
}
注意:发送方式有两种
①session.getBasicRemote().sendText() 同步发送消息,会出现阻塞
②session.getAsyncRemote().sendText() 异步发送消息,不会出现阻塞
5、controller-页面路径
路径:com.guosh.longze.controller. CustController
package com.guosh.longze.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Auther: fengqx
* @Date: 2021/11/14 - 11 -14 - 14:32
* @Description: PACKAGE_NAME
* @Version: 1.0
*/
@Controller
public class CustController {
@RequestMapping("/hello")
public String hello() {
System.out.println("进入hello");
return "hello";
}
@RequestMapping("/myWebservice")
public String myWebservice() {
System.out.println("进入websocket聊天室1");
return "webSocketTest";
}
}
6、html静态文件-前端
路径:resources/templates/ WebSocketTest.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>My WebSocket</title>
<style>
#message {
margin-top: 40px;
border: 1px solid gray;
padding: 20px;
}
</style>
</head>
<body>
昵称: <input type="text" id="nickname"/>
<button onclick="conectWebSocket()">连接WebSocket</button>
<button onclick="closeWebSocket()">断开连接</button>
<hr/>
<br/> 消息:<input id="text" type="text"/> 频道号:<input id="toUser" type="text" />
<button onclick="send()">发送消息</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
function conectWebSocket() {
var nickname = document.getElementById("nickname").value;
if(nickname===""){
alert("请输入昵称");
return;
}
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/myWebsocket/"+nickname);
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
setMessageInnerHTML("Loc MSG: 成功建立连接");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("Loc MSG:关闭连接");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
//获取输入的文本信息进行发送
var message = document.getElementById('text').value;
var toUser = document.getElementById('toUser').value;
var socketMsg = {msg:message,toUser:toUser};
if(toUser == ''){
//群聊.
socketMsg.type = 0;
}else{
//单聊.
socketMsg.type = 1;
}
websocket.send(JSON.stringify(socketMsg));
}
</script>
</html>
7、配置文件
application.properties
#指明 thymeleaf 查找view资源的根目录。默认是 /templates/ 目录。
spring.thymeleaf.prefix=classpath:/templates/
#指明 thymeleaf 查找view 资源时候使用的 后缀。默认是 html文件。
spring.thymeleaf.suffix=.html
三、功能联调
启动Main函数,开启三个浏览器。访问 http://localhost:8080/myWebservice
聊天一:
聊天二:
聊天三