官网介绍

🌐 http://www.websocket.org
The HTML5 WebSockets specification defines an API that enables web pages to use the WebSockets protocol for two-way communication with a remote host. It introduces the WebSocket interface and defines a full-duplex communication channel that operates through a single socket over the Web. HTML5 WebSockets provide an enormous reduction in unnecessary network traffic and latency compared to the unscalable polling and long-polling solutions that were used to simulate a full-duplex connection by maintaining two connections.
HTML5 WebSockets account for network hazards such as proxies and firewalls, making streaming possible over any connection, and with the ability to support upstream and downstream communications over a single connection, HTML5 WebSockets-based applications place less burden on servers, allowing existing machines to support more concurrent connections. The following figure shows a basic WebSocket-based architecture in which browsers use a WebSocket connection for full-duplex, direct communication with remote hosts.

💡 维基百科
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为RFC 6455,并由RFC 7936补充规范。WebScoket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebScoket API中,浏览器和服务器只需要完成一次握手,两者之前就直接创建持久性的连接,并进行双向数据传输。

项目准备

使用maven构建项目:

  1. <properties>
  2. <maven.compiler.source>1.8</maven.compiler.source>
  3. <maven.compiler.target>1.8</maven.compiler.target>
  4. <spring.boot.version>2.2.2.RELEASE</spring.boot.version>
  5. </properties>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-websocket</artifactId>
  10. <version>${spring.boot.version}</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  15. <version>${spring.boot.version}</version>
  16. </dependency>
  17. </dependencies>
  18. <build>
  19. <plugins>
  20. <plugin>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-maven-plugin</artifactId>
  23. </plugin>
  24. </plugins>
  25. </build>

application.properties如下:

  1. # Server
  2. server.port=3333
  3. # Thymeleaf
  4. spring.thymeleaf.prefix=classpath:/view/

后端编码

CustomEndpointConfigure

  1. import org.springframework.beans.BeansException;
  2. import org.springframework.beans.factory.BeanFactory;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import javax.websocket.server.ServerEndpointConfig;
  6. /**
  7. * @author KHighness
  8. * @since 2021-04-05
  9. */
  10. public class CustomEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
  11. private static volatile BeanFactory context;
  12. @Override
  13. public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
  14. return context.getBean(clazz);
  15. }
  16. @Override
  17. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  18. CustomEndpointConfigure.context = applicationContext;
  19. }
  20. }

WebSocketConfigure

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. /**
  5. * @author KHighness
  6. * @since 2021-04-05
  7. */
  8. @Configuration
  9. public class WebSocketConfigure {
  10. /**
  11. * 扫描并注册所有携带@ServerEndpoint注解的实例
  12. */
  13. @Bean
  14. public ServerEndpointExporter serverEndpointExporter() {
  15. return new ServerEndpointExporter();
  16. }
  17. @Bean
  18. public CustomEndpointConfigure customEndpointConfigure() {
  19. return new CustomEndpointConfigure();
  20. }
  21. }

CommonController

  1. import org.springframework.web.bind.annotation.PathVariable;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. import org.springframework.web.servlet.ModelAndView;
  5. import top.parak.websocket.WebSocketServer;
  6. import javax.websocket.Session;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Map;
  10. /**
  11. * @author KHighness
  12. * @since 2021-04-05
  13. */
  14. @RestController
  15. @RequestMapping("/websocket")
  16. public class CommonController {
  17. /**
  18. * 登录
  19. */
  20. @RequestMapping("/login/{username}")
  21. public ModelAndView login(@PathVariable("username") String username) {
  22. return new ModelAndView("socketChart.html", "username", username);
  23. }
  24. /**
  25. * 登出
  26. */
  27. @RequestMapping("/logout/{username}")
  28. public String logout(@PathVariable("username") String username) {
  29. return username + "退出成功";
  30. }
  31. /**
  32. * 获取在线用户
  33. */
  34. @RequestMapping("/getOnlineList")
  35. public List<String> getOnlineList(String username) {
  36. List<String> list = new ArrayList<>();
  37. for (Map.Entry<String, Session> entry : WebSocketServer.sessionStorage.entrySet()) {
  38. if (!entry.getKey().equals(username)) {
  39. list.add(entry.getKey());
  40. }
  41. }
  42. return list;
  43. }
  44. }

WebSockerServer

  1. import com.fasterxml.jackson.core.JsonProcessingException;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import top.parak.config.CustomEndpointConfigure;
  8. import javax.annotation.Resource;
  9. import javax.websocket.*;
  10. import javax.websocket.server.PathParam;
  11. import javax.websocket.server.ServerEndpoint;
  12. import java.io.IOException;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.concurrent.ConcurrentHashMap;
  16. import java.util.concurrent.atomic.AtomicLong;
  17. /**
  18. * @author KHighness
  19. * @since 2021-04-05
  20. */
  21. @RestController
  22. @RequestMapping("/websocket")
  23. @ServerEndpoint(value = "/websocket/{username}", configurator = CustomEndpointConfigure.class)
  24. public class WebSocketServer {
  25. private Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
  26. @Resource
  27. private ObjectMapper objectMapper;
  28. /**
  29. * 在线人数
  30. */
  31. public static AtomicLong onlineCount = new AtomicLong();
  32. /**
  33. * 在线用户
  34. * key:username,value:session
  35. */
  36. public static Map<String, Session> sessionStorage = new ConcurrentHashMap<>();
  37. /**
  38. * 连接建立成功调用
  39. */
  40. @OnOpen
  41. public void onOpen(Session session, @PathParam("username") String username) {
  42. // 用户上线
  43. sessionStorage.put(username, session);
  44. // 数量增加
  45. WebSocketServer.onlineCount.incrementAndGet();
  46. // 群发消息
  47. try {
  48. // 构建消息
  49. Map<String, Object> map = new HashMap<>();
  50. map.put("type", "onlineCount");
  51. map.put("onlineCount", onlineCount.get());
  52. map.put("username", username);
  53. sendMessage(session, objectMapper.writeValueAsString(map));
  54. } catch (JsonProcessingException e) {
  55. logger.error(e.getMessage());
  56. }
  57. logger.info("用户{}上线,SESSION_ID = {}", username, session.getId());
  58. }
  59. /**
  60. * 连接关闭调用
  61. */
  62. @OnClose
  63. public void onClose(Session session) {
  64. String username = "";
  65. for (Map.Entry<String, Session> entry : sessionStorage.entrySet()) {
  66. if (entry.getValue() == session) {
  67. username = entry.getKey();
  68. // 移除用户
  69. sessionStorage.remove(username);
  70. // 数量减少
  71. onlineCount.decrementAndGet();
  72. break;
  73. }
  74. }
  75. logger.info("用户{}下线,SESSION_ID = {}", username, session.getId());
  76. }
  77. /**
  78. * 收到客户端消息调用
  79. */
  80. @OnMessage
  81. public void onMessage(Session session, String message) {
  82. // json -> hashmap
  83. try {
  84. HashMap hashMap = objectMapper.readValue(message, HashMap.class);
  85. Map srcUser = (Map) hashMap.get("srcUser");
  86. Map tarUser = (Map) hashMap.get("tarUser");
  87. // 如果点击自己,则为群聊
  88. if (srcUser.get("username").equals(tarUser.get("username"))) {
  89. groupChat(session, hashMap);
  90. } else { // 私聊
  91. privateChat(session, tarUser, hashMap);
  92. }
  93. } catch (JsonProcessingException e) {
  94. logger.error(e.getMessage());
  95. }
  96. }
  97. /**
  98. * 发生错误调用
  99. */
  100. @OnError
  101. public void onError(Session session, Throwable error) {
  102. logger.error(error.getMessage());
  103. }
  104. /**
  105. * 群发
  106. */
  107. private void sendMessage(Session session, String message) {
  108. for (Map.Entry<String, Session> entry : sessionStorage.entrySet()) {
  109. try {
  110. if (entry.getValue() != session) {
  111. entry.getValue().getBasicRemote().sendText(message);
  112. }
  113. } catch (IOException e) {
  114. logger.error(e.getMessage());
  115. }
  116. }
  117. }
  118. /**
  119. * 私聊
  120. */
  121. private void privateChat(Session session, Map target, HashMap message) {
  122. Session targetSession = sessionStorage.get(target.get("username"));
  123. if (targetSession == null) { // 目标用户不在线,向自己发送<对方不在线>
  124. try {
  125. // 构建消息
  126. Map<String, Object> map = new HashMap<>();
  127. map.put("type", "0");
  128. map.put("message", "对方不在线");
  129. session.getBasicRemote().sendText(objectMapper.writeValueAsString(map));
  130. } catch (IOException e) {
  131. logger.error(e.getMessage());
  132. }
  133. } else {
  134. try {
  135. message.put("type", "1");
  136. targetSession.getBasicRemote().sendText(new ObjectMapper().writeValueAsString(message));
  137. } catch (IOException e) {
  138. logger.error(e.getMessage());
  139. }
  140. }
  141. }
  142. /**
  143. * 群聊
  144. */
  145. private void groupChat(Session session, HashMap hashMap) {
  146. for (Map.Entry<String, Session> entry : sessionStorage.entrySet()) {
  147. if (entry.getValue() != session) {
  148. try {
  149. hashMap.put("type", "2");
  150. entry.getValue().getBasicRemote().sendText(new ObjectMapper().writeValueAsString(hashMap));
  151. } catch (IOException e) {
  152. logger.error(e.getMessage());
  153. }
  154. }
  155. }
  156. }
  157. }

KHighnessApplication

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.scheduling.annotation.EnableAsync;
  4. /**
  5. * @author KHighness
  6. * @since 2021-04-05
  7. */
  8. @EnableAsync
  9. @SpringBootApplication
  10. public class KHighnessApplication {
  11. public static void main(String[] args) {
  12. SpringApplication.run(KHighnessApplication.class, args);
  13. }
  14. }

前端编码

socketChart.css

  1. body{
  2. background-color: #efebdc;
  3. }
  4. #hz-main{
  5. width: 700px;
  6. height: 500px;
  7. background-color: red;
  8. margin: 0 auto;
  9. }
  10. #hz-message{
  11. width: 500px;
  12. height: 500px;
  13. float: left;
  14. background-color: #B5B5B5;
  15. }
  16. #hz-message-body{
  17. width: 460px;
  18. height: 340px;
  19. background-color: #E0C4DA;
  20. padding: 10px 20px;
  21. overflow:auto;
  22. }
  23. #hz-message-input{
  24. width: 500px;
  25. height: 99px;
  26. background-color: white;
  27. overflow:auto;
  28. }
  29. #hz-group{
  30. width: 200px;
  31. height: 500px;
  32. background-color: rosybrown;
  33. float: right;
  34. }
  35. .hz-message-list{
  36. min-height: 30px;
  37. margin: 10px 0;
  38. }
  39. .hz-message-list-text{
  40. padding: 7px 13px;
  41. border-radius: 15px;
  42. width: auto;
  43. max-width: 85%;
  44. display: inline-block;
  45. }
  46. .hz-message-list-username{
  47. margin: 0;
  48. }
  49. .hz-group-body{
  50. overflow:auto;
  51. }
  52. .hz-group-list{
  53. padding: 10px;
  54. }
  55. .left{
  56. float: left;
  57. color: #595a5a;
  58. background-color: #ebebeb;
  59. }
  60. .right{
  61. float: right;
  62. color: #f7f8f8;
  63. background-color: #919292;
  64. }
  65. .hz-badge{
  66. width: 20px;
  67. height: 20px;
  68. background-color: #FF5722;
  69. border-radius: 50%;
  70. float: right;
  71. color: white;
  72. text-align: center;
  73. line-height: 20px;
  74. font-weight: bold;
  75. opacity: 0;
  76. }

socketChart.js

  1. //消息对象数组
  2. var msgObjArr = new Array();
  3. var websocket = null;
  4. //判断当前浏览器是否支持WebSocket, springboot是项目名
  5. if ('WebSocket' in window) {
  6. websocket = new WebSocket("ws://localhost:3333/websocket/"+username);
  7. } else {
  8. console.error("不支持WebSocket");
  9. }
  10. //连接发生错误的回调方法
  11. websocket.onerror = function (e) {
  12. console.error("WebSocket连接发生错误");
  13. };
  14. //连接成功建立的回调方法
  15. websocket.onopen = function () {
  16. //获取所有在线用户
  17. $.ajax({
  18. type: 'post',
  19. url: ctx + "/websocket/getOnlineList",
  20. contentType: 'application/json;charset=utf-8',
  21. dataType: 'json',
  22. data: {username:username},
  23. success: function (data) {
  24. if (data.length) {
  25. //列表
  26. for (var i = 0; i < data.length; i++) {
  27. var userName = data[i];
  28. $("#hz-group-body").append("<div class=\"hz-group-list\"><span class='hz-group-list-username'>" + userName + "</span><span id=\"" + userName + "-status\">[在线]</span><div id=\"hz-badge-" + userName + "\" class='hz-badge'>0</div></div>");
  29. }
  30. //在线人数
  31. $("#onlineCount").text(data.length);
  32. }
  33. },
  34. error: function (xhr, status, error) {
  35. console.log("ajax错误!");
  36. }
  37. });
  38. }
  39. //接收到消息的回调方法
  40. websocket.onmessage = function (event) {
  41. var messageJson = eval("(" + event.data + ")");
  42. //普通消息(私聊)
  43. if (messageJson.type == "1") {
  44. //来源用户
  45. var srcUser = messageJson.srcUser;
  46. //目标用户
  47. var tarUser = messageJson.tarUser;
  48. //消息
  49. var message = messageJson.message;
  50. //最加聊天数据
  51. setMessageInnerHTML(srcUser.username,srcUser.username, message);
  52. }
  53. //普通消息(群聊)
  54. if (messageJson.type == "2"){
  55. //来源用户
  56. var srcUser = messageJson.srcUser;
  57. //目标用户
  58. var tarUser = messageJson.tarUser;
  59. //消息
  60. var message = messageJson.message;
  61. //最加聊天数据
  62. setMessageInnerHTML(username,tarUser.username, message);
  63. }
  64. //对方不在线
  65. if (messageJson.type == "0"){
  66. //消息
  67. var message = messageJson.message;
  68. $("#hz-message-body").append(
  69. "<div class=\"hz-message-list\" style='text-align: center;'>" +
  70. "<div class=\"hz-message-list-text\">" +
  71. "<span>" + message + "</span>" +
  72. "</div>" +
  73. "</div>");
  74. }
  75. //在线人数
  76. if (messageJson.type == "onlineCount") {
  77. //取出username
  78. var onlineCount = messageJson.onlineCount;
  79. var userName = messageJson.username;
  80. var oldOnlineCount = $("#onlineCount").text();
  81. //新旧在线人数对比
  82. if (oldOnlineCount < onlineCount) {
  83. if($("#" + userName + "-status").length > 0){
  84. $("#" + userName + "-status").text("[在线]");
  85. }else{
  86. $("#hz-group-body").append("<div class=\"hz-group-list\"><span class='hz-group-list-username'>" + userName + "</span><span id=\"" + userName + "-status\">[在线]</span><div id=\"hz-badge-" + userName + "\" class='hz-badge'>0</div></div>");
  87. }
  88. } else {
  89. //有人下线
  90. $("#" + userName + "-status").text("[离线]");
  91. }
  92. $("#onlineCount").text(onlineCount);
  93. }
  94. }
  95. //连接关闭的回调方法
  96. websocket.onclose = function () {
  97. //alert("WebSocket连接关闭");
  98. }
  99. //将消息显示在对应聊天窗口 对于接收消息来说这里的toUserName就是来源用户,对于发送来说则相反
  100. function setMessageInnerHTML(srcUserName,msgUserName, message) {
  101. //判断
  102. var childrens = $("#hz-group-body").children(".hz-group-list");
  103. var isExist = false;
  104. for (var i = 0; i < childrens.length; i++) {
  105. var text = $(childrens[i]).find(".hz-group-list-username").text();
  106. if (text == srcUserName) {
  107. isExist = true;
  108. break;
  109. }
  110. }
  111. if (!isExist) {
  112. //追加聊天对象
  113. msgObjArr.push({
  114. toUserName: srcUserName,
  115. message: [{username: msgUserName, message: message, date: NowTime()}]//封装数据
  116. });
  117. $("#hz-group-body").append("<div class=\"hz-group-list\"><span class='hz-group-list-username'>" + srcUserName + "</span><span id=\"" + srcUserName + "-status\">[在线]</span><div id=\"hz-badge-" + srcUserName + "\" class='hz-badge'>0</div></div>");
  118. } else {
  119. //取出对象
  120. var isExist = false;
  121. for (var i = 0; i < msgObjArr.length; i++) {
  122. var obj = msgObjArr[i];
  123. if (obj.toUserName == srcUserName) {
  124. //保存最新数据
  125. obj.message.push({username: msgUserName, message: message, date: NowTime()});
  126. isExist = true;
  127. break;
  128. }
  129. }
  130. if (!isExist) {
  131. //追加聊天对象
  132. msgObjArr.push({
  133. toUserName: srcUserName,
  134. message: [{username: msgUserName, message: message, date: NowTime()}]//封装数据
  135. });
  136. }
  137. }
  138. // 对于接收消息来说这里的toUserName就是来源用户,对于发送来说则相反
  139. var username = $("#toUserName").text();
  140. //刚好打开的是对应的聊天页面
  141. if (srcUserName == username) {
  142. $("#hz-message-body").append(
  143. "<div class=\"hz-message-list\">" +
  144. "<p class='hz-message-list-username'>"+msgUserName+":</p>" +
  145. "<div class=\"hz-message-list-text left\">" +
  146. "<span>" + message + "</span>" +
  147. "</div>" +
  148. "<div style=\" clear: both; \"></div>" +
  149. "</div>");
  150. } else {
  151. //小圆点++
  152. var conut = $("#hz-badge-" + srcUserName).text();
  153. $("#hz-badge-" + srcUserName).text(parseInt(conut) + 1);
  154. $("#hz-badge-" + srcUserName).css("opacity", "1");
  155. }
  156. }
  157. //发送消息
  158. function send() {
  159. //消息
  160. var message = $("#hz-message-input").html();
  161. //目标用户名
  162. var tarUserName = $("#toUserName").text();
  163. //登录用户名
  164. var srcUserName = $("#talks").text();
  165. websocket.send(JSON.stringify({
  166. "type": "1",
  167. "tarUser": {"username": tarUserName},
  168. "srcUser": {"username": srcUserName},
  169. "message": message
  170. }));
  171. $("#hz-message-body").append(
  172. "<div class=\"hz-message-list\">" +
  173. "<div class=\"hz-message-list-text right\">" +
  174. "<span>" + message + "</span>" +
  175. "</div>" +
  176. "</div>");
  177. $("#hz-message-input").html("");
  178. //取出对象
  179. if (msgObjArr.length > 0) {
  180. var isExist = false;
  181. for (var i = 0; i < msgObjArr.length; i++) {
  182. var obj = msgObjArr[i];
  183. if (obj.toUserName == tarUserName) {
  184. //保存最新数据
  185. obj.message.push({username: srcUserName, message: message, date: NowTime()});
  186. isExist = true;
  187. break;
  188. }
  189. }
  190. if (!isExist) {
  191. //追加聊天对象
  192. msgObjArr.push({
  193. toUserName: tarUserName,
  194. message: [{username: srcUserName, message: message, date: NowTime()}]//封装数据[{username:huanzi,message:"你好,我是欢子!",date:2018-04-29 22:48:00}]
  195. });
  196. }
  197. } else {
  198. //追加聊天对象
  199. msgObjArr.push({
  200. toUserName: tarUserName,
  201. message: [{username: srcUserName, message: message, date: NowTime()}]//封装数据[{username:huanzi,message:"你好,我是欢子!",date:2018-04-29 22:48:00}]
  202. });
  203. }
  204. }
  205. //监听点击用户
  206. $("body").on("click", ".hz-group-list", function () {
  207. $(".hz-group-list").css("background-color", "");
  208. $(this).css("background-color", "whitesmoke");
  209. $("#toUserName").text($(this).find(".hz-group-list-username").text());
  210. //清空旧数据,从对象中取出并追加
  211. $("#hz-message-body").empty();
  212. $("#hz-badge-" + $("#toUserName").text()).text("0");
  213. $("#hz-badge-" + $("#toUserName").text()).css("opacity", "0");
  214. if (msgObjArr.length > 0) {
  215. for (var i = 0; i < msgObjArr.length; i++) {
  216. var obj = msgObjArr[i];
  217. if (obj.toUserName == $("#toUserName").text()) {
  218. //追加数据
  219. var messageArr = obj.message;
  220. if (messageArr.length > 0) {
  221. for (var j = 0; j < messageArr.length; j++) {
  222. var msgObj = messageArr[j];
  223. var leftOrRight = "right";
  224. var message = msgObj.message;
  225. var msgUserName = msgObj.username;
  226. var toUserName = $("#toUserName").text();
  227. //当聊天窗口与msgUserName的人相同,文字在左边(对方/其他人),否则在右边(自己)
  228. if (msgUserName == toUserName) {
  229. leftOrRight = "left";
  230. }
  231. //但是如果点击的是自己,群聊的逻辑就不太一样了
  232. if (username == toUserName && msgUserName != toUserName) {
  233. leftOrRight = "left";
  234. }
  235. if (username == toUserName && msgUserName == toUserName) {
  236. leftOrRight = "right";
  237. }
  238. var magUserName = leftOrRight == "left" ? "<p class='hz-message-list-username'>"+msgUserName+":</p>" : "";
  239. $("#hz-message-body").append(
  240. "<div class=\"hz-message-list\">" +
  241. magUserName+
  242. "<div class=\"hz-message-list-text " + leftOrRight + "\">" +
  243. "<span>" + message + "</span>" +
  244. "</div>" +
  245. "<div style=\" clear: both; \"></div>" +
  246. "</div>");
  247. }
  248. }
  249. break;
  250. }
  251. }
  252. }
  253. });
  254. //获取当前时间
  255. function NowTime() {
  256. var time = new Date();
  257. var year = time.getFullYear();//获取年
  258. var month = time.getMonth() + 1;//或者月
  259. var day = time.getDate();//或者天
  260. var hour = time.getHours();//获取小时
  261. var minu = time.getMinutes();//获取分钟
  262. var second = time.getSeconds();//或者秒
  263. var data = year + "-";
  264. if (month < 10) {
  265. data += "0";
  266. }
  267. data += month + "-";
  268. if (day < 10) {
  269. data += "0"
  270. }
  271. data += day + " ";
  272. if (hour < 10) {
  273. data += "0"
  274. }
  275. data += hour + ":";
  276. if (minu < 10) {
  277. data += "0"
  278. }
  279. data += minu + ":";
  280. if (second < 10) {
  281. data += "0"
  282. }
  283. data += second;
  284. return data;
  285. }

socketChart.html

  1. <!DOCTYPE>
  2. <!--解决idea thymeleaf 表达式模板报红波浪线-->
  3. <!--suppress ALL -->
  4. <html xmlns:th="http://www.thymeleaf.org">
  5. <head>
  6. <title>聊天页面</title>
  7. <!-- jquery在线版本 -->
  8. <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
  9. <!--引入样式-->
  10. <link th:href="@{/css/socketChart.css}" rel="stylesheet" type="text/css"/>
  11. </head>
  12. <body>
  13. <div id="hz-main">
  14. <div id="hz-message">
  15. <!-- 头部 -->
  16. 正在与<span id="toUserName"></span>聊天
  17. <hr style="margin: 0px;"/>
  18. <!-- 主体 -->
  19. <div id="hz-message-body">
  20. </div>
  21. <!-- 功能条 -->
  22. <div id="">
  23. <button>表情</button>
  24. <button>图片</button>
  25. <button id="videoBut">视频</button>
  26. <button onclick="send()" style="float: right;">发送</button>
  27. </div>
  28. <!-- 输入框 -->
  29. <div contenteditable="true" id="hz-message-input">
  30. </div>
  31. </div>
  32. <div id="hz-group">
  33. 登录用户:<span id="talks" th:text="${username}">请登录</span>
  34. <br/>
  35. 在线人数:<span id="onlineCount">0</span>
  36. <!-- 主体 -->
  37. <div id="hz-group-body">
  38. </div>
  39. </div>
  40. </div>
  41. </body>
  42. <script type="text/javascript" th:inline="javascript">
  43. //项目路径
  44. ctx = [[${#request.getContextPath()}]];
  45. //登录名
  46. var username = /*[[${username}]]*/'';
  47. </script>
  48. <script th:src="@{/js/socketChart.js}"></script>
  49. </html>

实现效果

私聊
image.png

群聊
image.png