SpringBoot+WebSocket实现服务端、客户端

一、引言

本人最近一直在使用springboot框架开发项目,毕竟现在很多公司都在采用此框架,之后本人也会陆续写关于springboot开发常用功能的文章。 

什么场景下会要使用到websocket的呢?

websocket主要功能就是实现网络通讯,比如说最经典的客服聊天窗口、您有新的消息通知,或者是项目与项目之间的通讯,都可以采用websocket来实现。

二、websocket介绍

在公司实际使用websocket开发,一般来都是这样的架构,首先websocket服务端是一个单独的项目,其他需要通讯的项目都是以客户端来连接,由服务端控制消息的发送方式(群发、指定发送)。 但是也会有服务端、客户端在同一个项目当中,具体看项目怎么使用。

本文呢,采用的是服务端与客户端分离来实现,包括使用springboot搭建websokcet服务端、html5客户端、springboot后台客户端, 具体看下面代码。

三、服务端实现

步骤一: springboot底层帮我们自动配置了websokcet,引入maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

步骤二:如果是你采用springboot内置容器启动项目的,则需要配置一个Bean。如果是采用外部的容器,则可以不需要配置。

/**
 * @Description: 配置类
 */
@Component
public class WebSocketConfig {
 
    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 步骤三:最后一步当然是编写服务端核心代码了,其实本人不是特别想贴代码出来,贴很多代码影响文章可读性。

package com.example.socket.code;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @Description: websocket 服务类
 */
 
/**
 *
 * @ServerEndpoint 这个注解有什么作用?
 *
 * 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端
 * 注解的值用户客户端连接访问的URL地址
 *
 */
 
@Slf4j
@Component
@ServerEndpoint("/websocket/{name}")
public class WebSocket {
 
    /**
     *  与某个客户端的连接对话,需要通过它来给客户端发送消息
     */
    private Session session;
 
     /**
     * 标识当前连接客户端的用户名
     */
    private String name;
 
    /**
     *  用于存所有的连接服务的客户端,这个对象存储是安全的
     */
    private static ConcurrentHashMap<String,WebSocket> webSocketSet = new ConcurrentHashMap<>();
 
 
    @OnOpen
    public void OnOpen(Session session, @PathParam(value = "name") String name){
        this.session = session;
        this.name = name;
        // name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分
        webSocketSet.put(name,this);
        log.info("[WebSocket] 连接成功,当前连接人数为:={}",webSocketSet.size());
    }
 
 
    @OnClose
    public void OnClose(){
        webSocketSet.remove(this.name);
        log.info("[WebSocket] 退出成功,当前连接人数为:={}",webSocketSet.size());
    }
 
    @OnMessage
    public void OnMessage(String message){
        log.info("[WebSocket] 收到消息:{}",message);
        //判断是否需要指定发送,具体规则自定义
        if(message.indexOf("TOUSER") == 0){
            String name = message.substring(message.indexOf("TOUSER")+6,message.indexOf(";"));
            AppointSending(name,message.substring(message.indexOf(";")+1,message.length()));
        }else{
            GroupSending(message);
        }
 
    }
 
    /**
     * 群发
     * @param message
     */
    public void GroupSending(String message){
        for (String name : webSocketSet.keySet()){
            try {
                webSocketSet.get(name).session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 指定发送
     * @param name
     * @param message
     */
    public void AppointSending(String name,String message){
        try {
            webSocketSet.get(name).session.getBasicRemote().sendText(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

四、客户端实现

HTML5实现:以下就是核心代码了,其实其他博客有很多,本人就不多说了。

 var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://192.168.2.107:8085/websocket/testname");
    }
 
    websocket.onopen = function(){
        console.log("连接成功");
    }
 
    websocket.onclose = function(){
        console.log("退出连接");
    }
 
    websocket.onmessage = function (event){
        console.log("收到消息"+event.data);
    }
 
    websocket.onerror = function(){
        console.log("连接出错");
    }
 
    window.onbeforeunload = function () {
        websocket.close(num);
    }

SpringBoot后台实现:本人发现多数博客都是采用js来实现客户端,很少有用后台来实现,所以本人也就写了写,大神请勿喷?。很多时候,项目与项目之间通讯也需要后台作为客户端来连接。

步骤一:首先我们要导入后台连接websocket的客户端依赖

<!--websocket作为客户端-->
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.3.5</version>
</dependency>

 步骤二:把客户端需要配置到springboot容器里面去,以便程序调用。

package com.example.socket.config;
 
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
 
import java.net.URI;
 
/**
 * @Description: 配置websocket后台客户端
 */
@Slf4j
@Component
public class WebSocketConfig {
 
    @Bean
    public WebSocketClient webSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8085/websocket/test"),new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[websocket] 连接成功");
                }
 
                @Override
                public void onMessage(String message) {
                    log.info("[websocket] 收到消息={}",message);
 
                }
 
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[websocket] 退出连接");
                }
 
                @Override
                public void onError(Exception ex) {
                    log.info("[websocket] 连接错误={}",ex.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
}

步骤三:使用后台客户端发送消息

1、首先本人写了一个接口,里面有指定发送和群发消息两个方法。

2、实现发送的接口,区分指定发送和群发由服务端来决定(本人在服务端写了,如果带有TOUSER标识的,则代表需要指定发送给某个websocket客户端)。

3、最后采用get方式用浏览器请求,也能正常发送消息。

package com.example.socket.code;
 
/**
 * @Description: websocket 接口
 */
public interface WebSocketService {
 
    /**
     * 群发
     * @param message
     */
     void groupSending(String message);
 
    /**
     * 指定发送
     * @param name
     * @param message
     */
     void appointSending(String name,String message);
}
package com.example.socket.chat;
 
import com.example.socket.code.ScoketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @Description: 测试后台websocket客户端
 */
@RestController
@RequestMapping("/websocket")
public class IndexController {
 
    @Autowired
    private ScoketClient webScoketClient;
 
    @GetMapping("/sendMessage")
    public String sendMessage(String message){
        webScoketClient.groupSending(message);
        return message;
    }
}

五、最后

注意:

如果是单例的情况下,这个对象的值都会被修改。

本人就抽了时间Debug了一下,经过下图也可以反映出,能够看出,webSokcetSet中存在三个成员,并且vlaue值都是不同的,所以在这里没有出现对象改变而把之前对象改变的现象。

服务端这样写是没问题的。

最后总结:在实际WebSocket服务端案例中为什么没有出现这种情况,当WebSokcet这个类标识为服务端的时候,每当有新的连接请求,这个类都是不同的对象,并非单例。

import com.alibaba.fastjson.JSON;
 
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @Description:
 */
public class TestMain {
 
    /**
     * 用于存所有的连接服务的客户端,这个对象存储是安全的
     */
    private static ConcurrentHashMap<String, Student> webSocketSet = new ConcurrentHashMap<>();
 
    public static void main(String[] args) {
        Student student = Student.getStudent();
        student.name = "张三";
        webSocketSet.put("1", student);
 
        Student students = Student.getStudent();
        students.name = "李四";
        webSocketSet.put("2", students);
 
        System.out.println(JSON.toJSON(webSocketSet));
    }
}
 
/**
 * 提供一个单例类
 */
class Student {
 
    public String name;
 
    private Student() {
    }
 
    private static final Student student = new Student();
 
    public static Student getStudent() {
        return student;
 
    }
}

 打印结果:

{"1":{"name":"李四"},"2":{"name":"李四"}}

原文地址:https://www.cnblogs.com/47Gamer/p/13628169.html