ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

WebSocket简单使用

2022-01-11 20:06:59  阅读:130  来源: 互联网

标签:WebSocket uuid 简单 log 使用 import websocket public socket


1.添加pom依赖

        <!-- WebSocket完成订单通知 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.代码

后端

package com.rocketmq.ws;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author liudean
 * @date 2022/1/11 14:54
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

package com.rocketmq.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

/**
 * @author liudean
 * 自定义返回格式
 * @date 2022/1/11 14:54
 */
public class ServerEncoder implements Encoder.Text<JSONObject> {
    @Override
    public String encode(JSONObject jsonObject){
        return JSON.toJSONString(jsonObject);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}


package com.rocketmq.ws;

import com.alibaba.fastjson.JSON;
import com.rocketmq.common.ResultMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liudean
 * @date 2022/1/11 14:52
 */
@Component
@ServerEndpoint(value = "/websocket/{uuid}",encoders = ServerEncoder.class)
public class WebSocketServer {
    public static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();

    private final Logger log = LoggerFactory.getLogger("WebSocketServer");

    /**
     * 连接建立成功调用的方法
     * */
    @OnOpen
    public void onOpen(Session session, @PathParam("uuid") String uuid) {
        log.info("客户端:" + uuid + "连接成功了");
        clients.put(uuid, session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("uuid") String uuid) {
        log.info("客户端:" + uuid + "断开连接了");
        clients.remove(uuid);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到客户端消息:"+message);

    }
    @OnError
    public void one rror(Throwable error) {
        error.printStackTrace();
    }


    /**
     * 测试
     * 实现服务器主动推送
     * 之后方法里面可通过建立连接的uuid推送到客户端
     */
    public void sendMessage(String uuid) throws IOException, EncodeException {
        Session session = WebSocketServer.clients.get(uuid);
        if (session != null) {
            System.out.println("连接成功,处理返回"+uuid);
            session.getBasicRemote().sendObject(JSON.toJSON(ResultMsg.SUCCESS.setNewData("我草,成功了")));
        } else {
            System.out.println("找不到客户端:"+uuid+"的连接");
        }
    }
}


前端

<template>
    <div>
        <el-row>
            <el-button type="success"  @click="onSubmit">成功按钮</el-button>
        </el-row>
    </div>
</template>
<script>

export default {
  data() {
    return {

    };
  },
  mounted() {

  },
  methods: {
    onSubmit() {
        let uuid = "8246666666"
          this.$axios
            .post("/send", {
              uuid: uuid,
            })
            .then((res) => {
              console.log(res);
              if (res.data.resultCode === 200) {
                //建立连接
                this.createSocket(uuid);
              } else {
                  alert(1)
              }
            });
    },
    createSocket(uuid){
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        let socketUrl = "ws://192.168.3.254:8021/websocket/" + uuid;
          if (socket != null) {
            socket.close();
            socket = null;
          }
          // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        //浏览器端收消息,获得从服务端发送过来的文本消息
        socket.onmessage = function(event) {
            console.log("返回了");
            console.log(event);
            var result = $.parseJSON(event.data);
            if(result.code === 200){
                
            }else{
                layer.msg(result.msg);
            }
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.log("Socket发生了错误");
        }
        //窗口关闭
        $(window).unload(function(event){
            socket.close();
        });
    }
    return socket;
}
  },
};
</script>

标签:WebSocket,uuid,简单,log,使用,import,websocket,public,socket
来源: https://blog.csdn.net/weixin_43851064/article/details/122440104

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有