• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

websocket使用前端和后端

武飞扬头像
络合
帮助1

目录

后端

导入依赖

编写数据载体

编写操作类

配置类

前端(HTML)


使用环境:jdk1.8 maven springboot

后端

导入依赖

在pom.xml文件的dependencies的标签里引入依赖

  1.  
    <dependency>
  2.  
    <!-- websocket -->
  3.  
    <groupId>org.springframework.boot</groupId>
  4.  
    <artifactId>spring-boot-starter-websocket</artifactId>
  5.  
    </dependency>

编写数据载体

消息内容的实体类

  1.  
    import java.io.Serializable;
  2.  
    public class SocketMessage implements Serializable {
  3.  
     
  4.  
    public static String IDENTITY="1";//身份确认
  5.  
    public static String HEART_BEAT="2";//心跳包
  6.  
    public static String SEND_MESSAGE="3";//消息
  7.  
    private static final long serialVersionUID = 4691408250677149975L;
  8.  
    private String data;
  9.  
    private String sendUserId;
  10.  
    private String sendType;
  11.  
     
  12.  
    public String getData() {
  13.  
    return data;
  14.  
    }
  15.  
     
  16.  
    public void setData(String data) {
  17.  
    this.data = data;
  18.  
    }
  19.  
     
  20.  
    public String getSendUserId() {
  21.  
    return sendUserId;
  22.  
    }
  23.  
     
  24.  
    public void setSendUserId(String sendUserId) {
  25.  
    this.sendUserId = sendUserId;
  26.  
    }
  27.  
     
  28.  
    public String getSendType() {
  29.  
    return sendType;
  30.  
    }
  31.  
     
  32.  
    public void setSendType(String sendType) {
  33.  
    this.sendType = sendType;
  34.  
    }
  35.  
    }
学新通

记录会话的实体类

  1.  
    import javax.websocket.Session;
  2.  
    import java.util.Date;
  3.  
     
  4.  
    public class SocketClient {
  5.  
     
  6.  
    private Session session;
  7.  
    private Date updateTime;
  8.  
     
  9.  
    public SocketClient() {
  10.  
    }
  11.  
     
  12.  
    public SocketClient(Session session, Date updateTime) {
  13.  
    this.session = session;
  14.  
    this.updateTime = updateTime;
  15.  
    }
  16.  
     
  17.  
    public Session getSession() {
  18.  
    return session;
  19.  
    }
  20.  
     
  21.  
    public void setSession(Session session) {
  22.  
    this.session = session;
  23.  
    }
  24.  
     
  25.  
    public Date getUpdateTime() {
  26.  
    return updateTime;
  27.  
    }
  28.  
     
  29.  
    public void setUpdateTime(Date updateTime) {
  30.  
    this.updateTime = updateTime;
  31.  
    }
  32.  
    }
学新通

编写操作类

由于通过websocke接收到的消息是字符串类型的消息,我们需要将字符串转为对应的实体类,可以通过gson来进行JSON数据与实体类间的转换(当然用其他的json转实体类的方法也行,我比较喜欢gson)

在pom.xml文件引入gson依赖

  1.  
    <dependency>
  2.  
    <groupId>com.谷歌.code.gson</groupId>
  3.  
    <artifactId>gson</artifactId>
  4.  
    <version>2.8.5</version>
  5.  
    </dependency>

操作类

  1.  
    package com.huzhiming.myapp.base.config.websocket;
  2.  
     
  3.  
    import com.谷歌.gson.Gson;
  4.  
    import com.谷歌.gson.GsonBuilder;
  5.  
    import org.springframework.stereotype.Component;
  6.  
    import javax.websocket.*;
  7.  
    import javax.websocket.server.ServerEndpoint;
  8.  
    import java.util.Date;
  9.  
    import java.util.Map;
  10.  
    import java.util.concurrent.ConcurrentHashMap;
  11.  
    import java.util.concurrent.atomic.AtomicInteger;
  12.  
     
  13.  
     
  14.  
    /**
  15.  
    * 一个简单的socket
  16.  
    */
  17.  
    @ServerEndpoint(value = "/mySocket")
  18.  
    @Component
  19.  
    public class SocketConnect {
  20.  
     
  21.  
    /**gson JSON字符串转实体类**/
  22.  
    public static Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
  23.  
     
  24.  
    /** 记录当前在线连接数 **/
  25.  
    public static AtomicInteger onlineCount = new AtomicInteger(0);
  26.  
     
  27.  
    /** 记录在线的客户端 **/
  28.  
    public static Map<String, SocketClient> clients = new ConcurrentHashMap<>();
  29.  
     
  30.  
    /**
  31.  
    * 有新的连接
  32.  
    * @param session
  33.  
    */
  34.  
    @OnOpen
  35.  
    public void onOpen(Session session){
  36.  
    System.out.println("新增连接");
  37.  
    }
  38.  
     
  39.  
    /**
  40.  
    * 收到客户端消息后调用的方法
  41.  
    * @param message
  42.  
    * 客户端发送过来的消息
  43.  
    */
  44.  
    @OnMessage
  45.  
    public void onMessage(String message, Session session) {
  46.  
    //将消息转换成实体类
  47.  
    SocketMessage socketMessage = gson.fromJson(message,SocketMessage.class);
  48.  
     
  49.  
    if(SocketMessage.IDENTITY.equals(socketMessage.getSendType())){
  50.  
    //身份认证
  51.  
    SocketClient socketClient = new SocketClient(session,new Date());
  52.  
    onlineCount.incrementAndGet();
  53.  
    clients.put(socketMessage.getSendUserId(), socketClient);
  54.  
    }else if(SocketMessage.HEART_BEAT.equals(socketMessage.getSendType())){
  55.  
    //心跳包
  56.  
    SocketClient socketClient = clients.get(socketMessage.getSendUserId());
  57.  
    if(socketClient !=null){
  58.  
    socketClient.setUpdateTime(new Date());
  59.  
    }
  60.  
    }else if(SocketMessage.SEND_MESSAGE.equals(socketMessage.getSendType())){
  61.  
    //发送的消息
  62.  
    if("1".equals(socketMessage.getMessageType())){
  63.  
    //单发
  64.  
    SocketClient socketClient = clients.get(socketMessage.getToUser());
  65.  
    socketClient.getSession().getAsyncRemote().sendText(message);
  66.  
    }else if("2".equals(socketMessage.getMessageType())){
  67.  
    //群发
  68.  
    for (Map.Entry<String, SocketClient> sessionEntry : clients.entrySet()) {
  69.  
    SocketClient toSession = sessionEntry.getValue();
  70.  
    // 排除掉自己
  71.  
    if (!sessionEntry.getKey().equals(socketMessage.getSendUserId())) {
  72.  
    toSession.getSession().getAsyncRemote().sendText(message);
  73.  
    }
  74.  
    }
  75.  
    }
  76.  
    }
  77.  
    }
  78.  
     
  79.  
     
  80.  
    /**
  81.  
    * 链接中断时
  82.  
    * @param session
  83.  
    * @param error
  84.  
    */
  85.  
    @OnError
  86.  
    public void onError(Session session, Throwable error) {
  87.  
    System.out.println("socket错误!");
  88.  
    }
  89.  
     
  90.  
     
  91.  
    /**
  92.  
    * 手动关闭了连接
  93.  
    * @param session
  94.  
    */
  95.  
    @OnClose
  96.  
    public void onClose(Session session){
  97.  
    String userId = "";
  98.  
    for (Map.Entry<String, SocketClient> sessionEntry : clients.entrySet()) {
  99.  
    SocketClient toSession = sessionEntry.getValue();
  100.  
    //根据session id判断是哪个用户关闭了连接
  101.  
    if(toSession.getSession().getId().equals(session.getId())){
  102.  
    userId = sessionEntry.getKey();
  103.  
    break;
  104.  
    }
  105.  
    }
  106.  
    System.out.println("用户离线" userId);
  107.  
    //在记录的客户端中移除该用户
  108.  
    clients.remove(userId);
  109.  
    onlineCount.decrementAndGet();
  110.  
    }
  111.  
     
  112.  
     
  113.  
     
  114.  
     
  115.  
     
  116.  
    }
学新通

配置类

  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.  
    @Configuration
  6.  
    public class SocketConfig {
  7.  
     
  8.  
    @Bean
  9.  
    public ServerEndpointExporter serverEndpointExporter() {
  10.  
    return new ServerEndpointExporter();
  11.  
    }
  12.  
    }

用于扫描带有@ServerEndpoint的注解,将改类注册为websocket服务

至此后端准备完毕,,运行springboot项目

前端(HTML)

用户id为1,发消息给id为2的用户

  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title></title>
  6.  
    </head>
  7.  
    <body>
  8.  
     
  9.  
    <input type="text" id="msg">
  10.  
    <button id="sendBtn" onclick="sendClick()">发送</button>
  11.  
    <button id="closeBtn" onclick="closeWebsocket()">关闭</button>
  12.  
    <div id="message">
  13.  
    </div>
  14.  
     
  15.  
     
  16.  
    </body>
  17.  
     
  18.  
    <script type="text/javascript">
  19.  
    var ws = null;
  20.  
    if ('WebSocket' in window){
  21.  
    //这里写自己项目启动后的地址
  22.  
    ws = new WebSocket("ws://localhost:80/myapp/mySocket")
  23.  
    }else {
  24.  
    alert("浏览器不支持");
  25.  
    }
  26.  
    var connBtn = document.getElementById("connBtn");
  27.  
    var sendBtn = document.getElementById("sendBtn");
  28.  
    var closeBtn = document.getElementById("closeBtn");
  29.  
     
  30.  
    // 连接安生错误的回调方法
  31.  
    ws.onerror = function () {
  32.  
    setMessageInnerHTML("WEBSOCKET发生链接错误");
  33.  
    }
  34.  
     
  35.  
    // 连接成功的回调方法
  36.  
    ws.onopen = function (ev) {
  37.  
    setMessageInnerHTML("WebSocket连接成功!");
  38.  
    let sendObject={
  39.  
    data:"",
  40.  
    sendUserId:"1",//当前用户id
  41.  
    sendType:"1"//身份验证
  42.  
    }
  43.  
    send(sendObject);
  44.  
    }
  45.  
     
  46.  
    // 收到消息的回调方法
  47.  
    ws.onmessage = function (ev) {
  48.  
    setMessageInnerHTML(ev.data);
  49.  
     
  50.  
    }
  51.  
     
  52.  
    // 连接关闭的回调方法
  53.  
    ws.onclose = function () {
  54.  
    setMessageInnerHTML("WebSocket连接关闭");
  55.  
    }
  56.  
     
  57.  
     
  58.  
    // 监听窗口关闭事件,防止连接没断关闭窗口。
  59.  
    window.onbeforeunload = function () {
  60.  
    closeWebSocket();
  61.  
    }
  62.  
     
  63.  
     
  64.  
    // 将消息显示在网页上
  65.  
    function setMessageInnerHTML(innerHtml){
  66.  
    document.getElementById("message").innerHTML = innerHtml '<br />'
  67.  
    }
  68.  
     
  69.  
    // 关闭websocket连接
  70.  
    function closeWebsocket(){
  71.  
    ws.close();
  72.  
    }
  73.  
    function sendClick(){
  74.  
    var message = document.getElementById("msg").value;
  75.  
    let sendObject={
  76.  
    data:message,//消息内容
  77.  
    sendType:"3",//发送消息
  78.  
    toUser:"2",
  79.  
    messageType:"1"//单发
  80.  
    }
  81.  
    send(sendObject);
  82.  
    }
  83.  
     
  84.  
    // 发送消息
  85.  
    function send(sendObject){
  86.  
    ws.send(JSON.stringify(sendObject));
  87.  
    }
  88.  
     
  89.  
    </script>
  90.  
    </html>
学新通

修改一下页面sendObject

用户id为2,给id为1用户发送消息

  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title></title>
  6.  
    </head>
  7.  
    <body>
  8.  
     
  9.  
    <input type="text" id="msg">
  10.  
    <button id="sendBtn" onclick="sendClick()">发送</button>
  11.  
    <button id="closeBtn" onclick="closeWebsocket()">关闭</button>
  12.  
    <div id="message">
  13.  
    </div>
  14.  
     
  15.  
     
  16.  
    </body>
  17.  
     
  18.  
    <script type="text/javascript">
  19.  
    var ws = null;
  20.  
    if ('WebSocket' in window){
  21.  
    ws = new WebSocket("ws://localhost:80/myapp/mySocket")
  22.  
    }else {
  23.  
    alert("浏览器不支持");
  24.  
    }
  25.  
    var connBtn = document.getElementById("connBtn");
  26.  
    var sendBtn = document.getElementById("sendBtn");
  27.  
    var closeBtn = document.getElementById("closeBtn");
  28.  
     
  29.  
    // 连接安生错误的回调方法
  30.  
    ws.onerror = function () {
  31.  
    setMessageInnerHTML("WEBSOCKET发生链接错误");
  32.  
    }
  33.  
     
  34.  
    // 连接成功的回调方法
  35.  
    ws.onopen = function (ev) {
  36.  
    setMessageInnerHTML("WebSocket连接成功!");
  37.  
    let sendObject={
  38.  
    data:"",
  39.  
    sendUserId:"2",//当前用户id
  40.  
    sendType:"1"//身份验证
  41.  
    }
  42.  
    send(sendObject);
  43.  
    }
  44.  
     
  45.  
    // 收到消息的回调方法
  46.  
    ws.onmessage = function (ev) {
  47.  
    setMessageInnerHTML(ev.data);
  48.  
     
  49.  
    }
  50.  
     
  51.  
    // 连接关闭的回调方法
  52.  
    ws.onclose = function () {
  53.  
    setMessageInnerHTML("WebSocket连接关闭");
  54.  
    }
  55.  
     
  56.  
     
  57.  
    // 监听窗口关闭事件,防止连接没断关闭窗口。
  58.  
    window.onbeforeunload = function () {
  59.  
    closeWebSocket();
  60.  
    }
  61.  
     
  62.  
     
  63.  
    // 将消息显示在网页上
  64.  
    function setMessageInnerHTML(innerHtml){
  65.  
    document.getElementById("message").innerHTML = innerHtml '<br />'
  66.  
    }
  67.  
     
  68.  
    // 关闭websocket连接
  69.  
    function closeWebsocket(){
  70.  
    ws.close();
  71.  
    }
  72.  
    function sendClick(){
  73.  
    var message = document.getElementById("msg").value;
  74.  
    let sendObject={
  75.  
    data:message,//消息内容
  76.  
    sendType:"3",//发送消息
  77.  
    toUser:"1",
  78.  
    messageType:"1"//单发
  79.  
    }
  80.  
    send(sendObject);
  81.  
    }
  82.  
     
  83.  
    // 发送消息
  84.  
    function send(sendObject){
  85.  
    ws.send(JSON.stringify(sendObject));
  86.  
    }
  87.  
     
  88.  
    </script>
  89.  
    </html>
学新通

学新通

学新通

一个简单websocket应用就完成啦。

这篇文章转载于:学新通

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通
  • 本文地址: https://www.swvq.com/boutique/detail/tanhehfeff
  • 联系方式: luke.wu●vfv.cc
系列文章
更多 icon
同类精品
更多 icon
我要评论
我的头像
精彩评论
继续加载