当前位置:   article > 正文

最简单入门的SpringBoot+Vue项目用WebSoket完整教程代码,做客服,即时通信的看过来!_vue3 怎么做在线客服

vue3 怎么做在线客服

后端原理不是很复杂 每次用户连接到服务端的时候会携带一个username,连接成功之后后端把username和当前soket添加到Map中

webSocketMap.put(username, this);
  • 1

需要给指定用户发送消息的时候就通过username获取WebSoketServer通过.getBasicRemote().sendText()向用户发送消息

 for (Map.Entry<String, SongWebSoketServer> server : webSocketMap.entrySet()) {
 	if(server.getKey().equals("接收消息的用户名")){
 		server.getValue().session.getBasicRemote().sendText("想要发送的消息");
 	}
 }
  • 1
  • 2
  • 3
  • 4
  • 5

需要发送复杂消息的情况下可以New一个JSON对象

	JSONObject jsonObject = new JSONObject();
	jsonObject.put("code", 200);
	jsonObject.put("message", message);
	jsonObject.toJSONString();
  • 1
  • 2
  • 3
  • 4

完整代码:

前端页面中比较简单

<template>
	<el-input v-model="content" />
	<el-button @click="send">发送</el-button>
</template>
<script>
export default {
  data() {
    return {
      socket: "",
      content: '',
    }
  },
  created() {
    this.init();
  },
  methods: {
    init: function () {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 需要服务器配置开放后端端口
        // 实例化socket
        this.socket = new WebSocket("ws://localhost:8080/websocket/" + "username");
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      console.log(msg)
    },
    send: function () {
    	this.socket.send(this.content);
    	this.content = "";
    },
    close: function () {
      console.log("socket已经关闭");
    }
  },
  destroyed() {
    this.socket.onclose = this.close; // 销毁监听
  }
}
</script>
<style lang="scss" scoped>
</style>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

SpirngBoot项目中创建WebSoket模块

pom中引入
 <!-- SpringBoot Websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
新建WebSoketServer
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

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

@Component
@Service
@ServerEndpoint(value = "/websocket/{username}")
public class WebSoketServer {
	static final Logger loggger = LoggerFactory.getLogger(WebSoketServer.class);
    private static ConcurrentHashMap<String, WebSoketServer> webSocketMap = new ConcurrentHashMap<>();  // 用来存放每个客户端对应的MyWebSocket对象。   
    private Session session;    
    private String username = "";   // 接收username
    // 打开连接
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) throws IOException {
        this.session = session;
        this.username = username;
        if (webSocketMap.containsKey(username)) {
            webSocketMap.remove(username);
            webSocketMap.put(username, this);
        } else {
            webSocketMap.put(username, this);
        }
        loggger.info("用户:" + username + "连接:当前在线人数为:" + webSocketMap.size());
    }
    // 关闭连接
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(username)) {
            webSocketMap.remove(username);
        }
        loggger.info("用户" + username + "退出:当前在线人数为:" + webSocketMap.size());
    }
    // 接收消息
    @OnMessage
    public void onMessage(String message, Session session) {
        loggger.info("用户" + username + "消息:内容:" + message);
    }
    // 发送自定义消息
    public static void sendInfo(String message, String username) {
        loggger.info("发送消息到:" + username + ",内容:" + message);
        if (StringUtils.isNotBlank(username) && webSocketMap.containsKey(username)) {
            try {
                webSocketMap.get(username).sendMessage(message);
            } catch (Exception e) {
                loggger.error(e.getMessage(), e);
            }
        } else {
            loggger.error("用户" + username + ",不在线!");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        loggger.error("用户" + username + "错误:原因:" + error.getMessage());
        error.printStackTrace();
    }
    // 推送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/576607
推荐阅读
相关标签
  

闽ICP备14008679号