多语言展示
当前在线:1207今日阅读:27今日分享:41

webscocket如何实现聊天功能

关于websocket如何实现实时聊天,一个小demo
工具/原料
1

eclipse,jdk1.8

2

Springboot

方法/步骤
1

搭建Springboot环境,导入相关webSocket依赖

2

建立index.html页面代码如下聊天室

消息:

3

建立控制器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'; }}

4

建立webSocket连接类连接代码如下@Component@ServerEndpoint('/websocket')public class WebSocket { // seesion.getId(), return 16进制的字符串 // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 static CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet(); // 与某个客户端的连接会话,需要通过它来给客户端发送数据 private static Session session;  /** * 连接建立成功调用的方法 *  * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(Session session) { this.session = session; webSockets.add(this); // 加入set中 addOnlineCount(); // 在线数加1 System.out.println('有新连接加入!当前在线人数为' + getOnlineCount() + ' --> ' + session.getId()); }  /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSockets.remove(this); // 从set中删除 subOnlineCount(); // 在线数减1 System.out.println('有一连接关闭!当前在线人数为' + getOnlineCount()); }  /** * 收到客户端消息后调用的方法,直接传入json格式的数据 *  * @param message 客户端发送过来的消息 * @param session 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println('来自客户端的消息:' + message); sendToCurr(message); }  // 群发消息 private void sendToAll(String message) { for (WebSocket item : webSockets) { try { sendInfoToWeb(message); } catch (Exception e) { e.printStackTrace(); continue; } } } // 发送给当前连接用户 public static void sendToCurr(String message) { try { sendInfoToWeb(message); } catch (Exception e) { e.printStackTrace(); } } /** * 发生错误时调用 *  * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println('发生错误'); error.printStackTrace(); }  /** * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 *  * @param message * @throws IOException */ public static void sendInfoToWeb(String message) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // this.session.getAsyncRemote().sendText(message); }  public static synchronized int getOnlineCount() { return onlineCount; }  private static synchronized void addOnlineCount() { WebSocket.onlineCount++; }  private static synchronized void subOnlineCount() { WebSocket.onlineCount--; } }

5

设置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 = {});

注意事项

百度复制下来,可能存在空格错误,需要自己删减一下

推荐信息