eclipse,jdk1.8
Springboot
搭建Springboot环境,导入相关webSocket依赖
建立index.html页面代码如下
建立控制器ChatController代码如下:package com.lc.controller; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; /** * @author MWEI E-mail: 574185505@qq.com* @version 2019年8月8日 下午4:58:32 * Class Explain: 聊天室*/@Controllerpublic class ChatController { @RequestMapping('index') public String index() { return 'index'; } //发送消息 @RequestMapping('sendMsg') @ResponseBody public String sendMsg(String msg) { System.out.println(msg); WebSocket.webSockets.forEach(obj -> WebSocket.sendToCurr(msg + '')); return '1'; }}
建立webSocket连接类连接代码如下@Component@ServerEndpoint('/websocket')public class WebSocket { // seesion.getId(), return 16进制的字符串 // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 static CopyOnWriteArraySet
设置js前缀处理ws.js代码如下:(function($) { // $.config = { // url : '', // 链接地址 // }; // $.init = function(config) { // this.config = config; // return this; // }; /** * 连接webcocket */ $.connect = function(url) { // 自动处理前缀 var protocol = (window.location.protocol == 'http:') ? 'ws:' : 'wss:'; this.host = protocol + url; window.WebSocket = window.WebSocket || window.MozWebSocket; if (!window.WebSocket) { // 检测浏览器支持 this.error('Error: WebSocket is not supported .'); return; } // 创建连接 this.socket = new WebSocket(this.host); // 注册响应函数 onopen, onmessage, onclose, onerror this.socket.onopen = function() { $.onopen(); }; this.socket.onmessage = function(message) { $.onmessage(message); }; this.socket.onclose = function() { $.onclose(); $.socket = null; // 清理 }; this.socket.onerror = function(errorMsg) { $.onerror(errorMsg); } return this; } /** * 自定义异常函数 * * @param {Object} * errorMsg */ $.error = function(errorMsg) { this.onerror(errorMsg); } /** * 消息发送 */ $.send = function(message) { if (this.socket) { this.socket.send(message); return true; } this.error('please connect to the server first !!!'); return false; } $.close = function() { if (this.socket != undefined && this.socket != null) { this.socket.close(); } else { this.error('this socket is not available'); } } /** * 消息回調 * * @param {Object} * message */ $.onmessage = function(message) { console.log('default callback : receive msg : ' + message.data); } /** * 链接回调函数 */ $.onopen = function() { console.log('websocket open success !'); } /** * 关闭回调 */ $.onclose = function() { console.log('websocket close success !'); } /** * 异常回调 */ $.onerror = function() { console.log('error happened !'); } })(ws = {});
百度复制下来,可能存在空格错误,需要自己删减一下