Springboot+websocket实现服务端、客户端

Easter79
• 阅读 1430

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

关注公众号后台回复paymall获取实战项目资料+视频

作者:IT贱男

来源:https://jiannan.blog.csdn.net/article/details/86352677

一、引言

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

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

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

二、websocket介绍

百度百科介绍:WebSokcet

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

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

三、服务端实现

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

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

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

`/**

 * @Auther: liaoshiyao
 * @Date: 2019/1/11 11:49
 * @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;

/**
 * @Auther: liaoshiyao
 * @Date: 2019/1/11 11:48
 * @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的客户端依赖

`

    org.java-websocket     Java-WebSocket     1.3.5 `

_*步骤二*_:把客户端需要配置到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;

/**
 * @Auther: liaoshiyao
 * @Date: 2019/1/11 17:38
 * @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;
/**
 * @Auther: liaoshiyao
 * @Date: 2019/1/12 10:57
 * @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.code;

import org.java_websocket.client.WebSocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Auther: liaoshiyao
 * @Date: 2019/1/12 10:56
 * @Description: websocket接口实现类
 */
@Component
public class ScoketClient implements WebSocketService{

    @Autowired
    private WebSocketClient webSocketClient;

    @Override
    public void groupSending(String message) {

        // 这里我加了6666-- 是因为我在index.html页面中,要拆分用户编号和消息的标识,只是一个例子而已
        // 在index.html会随机生成用户编号,这里相当于模拟页面发送消息
        // 实际这样写就行了 webSocketClient.send(message)
        webSocketClient.send(message+"---6666");
    }

    @Override
    public void appointSending(String name, String message) {

        // 这里指定发送的规则由服务端决定参数格式
        webSocketClient.send("TOUSER"+name+";"+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;

/**
 * @Auther: liaoshiyao
 * @Date: 2019/1/11 16:47
 * @Description: 测试后台websocket客户端

 */
@RestController
@RequestMapping("/websocket")
public class IndexController {

    @Autowired
    private ScoketClient webScoketClient;

    @GetMapping("/sendMessage")
    public String sendMessage(String message){
        webScoketClient.groupSending(message);
        return message;
    }
}
`

五、最后

其实,贴了这么多大一片的代码,感觉上影响了博客的美观,也不便于浏览,如果没看懂小伙伴,可以下载源码看下。

里面一共两个项目,服务端、客户端(html5客户端、后台客户端),是一个网页群聊的小案例。

https://download.csdn.net/download/weixin\_38111957/10912384

*祝大家学习愉快~~~*

六、针对评论区的小伙伴提出的疑点进行解答

看了小伙伴提出的疑问,小编也是非常认可的,如果是单例的情况下,这个对象的值都会被修改。

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

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

Springboot+websocket实现服务端、客户端

紧接着,小编写了一个测试类,代码如下,经过测试输出的结果和小伙伴提出的疑点是一致的。

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

这里也感谢“烟花苏柳”所提出的问题。

`import com.alibaba.fastjson.JSON;
import java.util.concurrent.ConcurrentHashMap;

/**

 * @Auther: IT贱男

 * @Date: 2018/11/1 16:15

 * @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":"李四"}}

Springboot+websocket实现服务端、客户端

Springboot+websocket实现服务端、客户端

有热门推荐👇

我设计了一个牛逼的轻量级搜索引擎

OAuth2和JWT - 如何设计安全的API?

淘宝的这款开源的代码质量检测工具(已开源),网友:太强大了~

这份2021Java程序员常用技术栈和工具清单,刷爆了朋友圈...

共享锁、排他锁、互斥锁、悲观锁、乐观锁、行锁、表锁、页面锁、不可重复读、丢失修改、读脏数据

牛逼的EasyExcel,让Excel导入导出更加简单,附详细教程!

SpringBoot 接口幂等性实现的4种方案!这个我真的服气了!

太牛逼了!项目中用了Disruptor之后,性能提升了2.5倍

Springboot+websocket实现服务端、客户端

点击阅读原文,前往学习SpringCloud实战项目

本文分享自微信公众号 - java版web项目(java_project)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
OAuth2和JWT
点击上方蓝色字体,选择“标星公众号”优质文章,第一时间送达关注公众号后台回复pay或mall获取实战项目资料视频作者:SanLiwww.pingfangushi.com/posts/9005/本文会详细描述两种通用的保证API安全性的方法:OAuth2和JSONWebToken(JWT
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Stella981 Stella981
2年前
ClickHouse大数据领域企业级应用实践和探索总结
点击上方蓝色字体,选择“设为星标”回复”资源“获取更多资源!(https://oscimg.oschina.net/oscnet/bb00e5f54a164cb9827f1dbccdf87443.jpg)!(https://oscimg.oschina.net/oscnet/dc8da835ff1b4
Stella981 Stella981
2年前
200的大额人民币即将面世?央行:Yes!
点击上方蓝字关注我们!(https://oscimg.oschina.net/oscnet/2a1c2ac00bf54458a78c48a6c2e547d5.png)点击上方“印象python”,选择“星标”公众号重磅干货,第一时间送达!!(
可莉 可莉
2年前
200的大额人民币即将面世?央行:Yes!
点击上方蓝字关注我们!(https://oscimg.oschina.net/oscnet/2a1c2ac00bf54458a78c48a6c2e547d5.png)点击上方“印象python”,选择“星标”公众号重磅干货,第一时间送达!!(
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k