一、聊天室模式
0.效果图:
1.后端代码
1.1 导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></exclusion></exclusions></dependency>
1.2 WebSocket工具类
package com.woniu.util;import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;public class WebSocketUtil {//放所有参与聊天的用户标识public static final Map<String, Session> messageMap = new ConcurrentHashMap<>();/***单个消息*/public static void send(Session session,String message){if (session != null){final RemoteEndpoint.Basic basic = session.getBasicRemote();if (basic != null){try {basic.sendText(message);} catch (IOException e) {e.printStackTrace();}}}}/*** 全体发消息*/public static void sendAll(String message){messageMap.forEach((userName,session) -> send(session,message));}}
1.3 WebSocket事件类
package com.woniu.webscoket;import com.woniu.util.WebSocketUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;@RestController
@ServerEndpoint("/WebSocketHandler/{userName}")
public class WebSocketHandler {@OnOpenpublic void openSession(@PathParam("userName") String userName, Session session){String message = "欢迎:"+userName +"加入群聊";WebSocketUtil.messageMap.put(userName,session);//给所有人发消息WebSocketUtil.sendAll(message);}@OnMessagepublic void onMessage(@PathParam("userName") String userName, String message){message = userName +":" +message;WebSocketUtil.sendAll(message);}@OnClosepublic void onClose(@PathParam("userName") String userName,Session session){WebSocketUtil.messageMap.remove(userName);WebSocketUtil.sendAll("用户:"+userName+"离开聊天室");try {session.close();} catch (IOException e) {e.printStackTrace();}}
}
1.4 WebSocketConfig 配置类, 并在主启动类上加上 @EnableWebSocket 注解
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}
1.5 如果用了网关或springSecurity 记得配白名单
2. 前端代码【完整】
<template><div><el-row><el-col :span="6" :offset="3"><h2 class="title">匿名聊天室</h2></el-col></el-row><el-row><el-col :span="12" :offset="1"><textareaid="textarea"class="chat-area"disabled="disabled"rows="10"cols="50"></textarea></el-col></el-row><el-row><el-col :span="6" :offset="1" class="input-col"><el-inputtype="text"placeholder="请输入用户名"v-model="userName"class="input-field"></el-input></el-col><el-col :span="4" class="send-col"><el-button type="primary" @click="join" class="button">进聊天室</el-button></el-col></el-row><el-row><el-col :span="6" :offset="1" class="message-col"><el-inputtype="text"placeholder="请输入消息"v-model="message"class="input-field"></el-input></el-col><el-col :span="4" class="send-col"><el-button type="success" @click="send" class="button">发送信息</el-button></el-col></el-row></div>
</template><script>
export default {data() {return {url: "ws://192.168.1.58:8085/WebSocketHandler/",ws: "",userName: "",message: "",};},methods: {join() {if (this.userName == "") {alert("请输入您的大名!");}this.ws = new WebSocket(this.url + this.userName);this.ws.onopen = function () {console.log("连接成功!");};this.ws.onmessage = function (result) {var textarea = document.getElementById("textarea");textarea.append(result.data + "\n");textarea.scrollTop = textarea.scrollHeight;};this.ws.onclose = function () {var textarea = document.getElementById("textarea");textarea.append("用户:" + this.userName + "离开聊天室 \n");console.log("");};},send() {if (this.ws != null) {this.ws.send(this.message);this.message = "";}},},
};
</script><style>
.title {font-size: 24px;margin-bottom: 16px;
}.chat-area {width: 100%;height: 200px;resize: none;
}.input-field {width: 95%;margin-bottom: 16px;
}.button {margin-left: 8px;
}
</style>
问题:
如果你在配置完成后, 出现这个提示
WebSocket connection to 'ws://xxx/WebSocketHandler/e' failed
要去检查一下,你在前端请求的端口是否正确。
二、私聊模式 (未完待续)
...