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

这篇具有很好参考价值的文章主要介绍了SpringBoot+WebSocket实现服务端、客户端。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、引言

小编最近一直在使用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的客户端依赖

<!--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;

/**
 * @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客户端,架构,spring boot,websocket,后端文章来源地址https://www.toymoban.com/news/detail-639728.html

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

最后总结:这位小伙伴提出的观点确实是正确的,但是在实际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客户端,架构,spring boot,websocket,后端

到了这里,关于SpringBoot+WebSocket实现服务端、客户端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot WebSocket做客户端

    常见的都是springboot应用做服务,前端页面做客户端,进行websocket通信进行数据传输交互。但其实springboot服务也能做客户端去连接别的webSocket服务提供者。 刚好最近在项目中就使用到了,需求背景大概就是我们作为一个java段应用需要和一个C语言应用进行通信。在项目需求及

    2024年02月11日
    浏览(34)
  • 快速搭建springboot websocket客户端

    WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。 HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。 HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。 浏览器通过 JavaSc

    2024年02月06日
    浏览(49)
  • SpringBoot2.0集成WebSocket,多客户端

    适用于单客户端,一个账号登陆一个客户端,登陆多个客户端会报错 The remote endpoint was in state [TEXT_FULL_WRITING]  这是因为此时的session是不同的,只能锁住一个session,解决此问题的方法把全局静态对象锁住,因为账号是唯一的

    2024年02月10日
    浏览(39)
  • Springboot 集成WebSocket作为客户端,含重连接功能,开箱即用

    使用演示 只需要init后调用sendMessage方法即可,做到开箱即用。内部封装了失败重连接、断线重连接等功能。 基于Springboot工程 引入websocket依赖 开箱即用的工具类

    2024年02月04日
    浏览(49)
  • springboot集成webstock实战:服务端数据推送数据到客户端实现实时刷新

        之前介绍过springboot集成webstock方式,具体参考: springboot集成websocket实战:站内消息实时推送 这里补充另外一个使用webstock的场景,方便其他同学理解和使用,废话不多说了,直接开始!简单介绍一下业务场景:     现在有一个投票活动,活动详情中会显示投票活动的参与人数、访

    2024年02月08日
    浏览(89)
  • netty学习(3):SpringBoot整合netty实现多个客户端与服务器通信

    创建一个SpringBoot工程,然后创建三个子模块 整体工程目录:一个server服务(netty服务器),两个client服务(netty客户端) pom文件引入netty依赖,springboot依赖 NettySpringBootApplication NettyServiceHandler SocketInitializer NettyServer NettyStartListener application.yml Client1 NettyClientHandler SocketInitializ

    2024年02月11日
    浏览(45)
  • SpringBoot中使用Netty实现TCP通讯,服务器主动向客户端发送数据

    Springboot项目的web服务后台,web服务运行在9100端口。 后台使用netty实现了TCP服务,运行在8000端口。 启动截图如下: 启动类修改: 服务器查看当前所有连接的客户端  服务器获取到所有客户单的ip地址及端口号后,即可通过其给指定客户端发送数据  

    2024年02月11日
    浏览(33)
  • SpringBoot+CAS整合服务端和客户端实现SSO单点登录与登出快速入门上手

    教学讲解视频地址:视频地址 因为CAS支持HTTP请求访问,而我们是快速入门上手视频,所以这期教程就不教大家如何配置HTTPS了,如果需要使用HTTPS,可以参考其他博客去云服务器申请证书或者使用JDK自行生成一个证书。 下载CAS Server(直接下载压缩包就可以) 这里我们用的是

    2024年02月02日
    浏览(46)
  • C++实现WebSocket通信(服务端和客户端)

    天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。 这里单纯是个人总结,如需更官方更准确的websocket介绍可百度 websocket是一种即时通讯协

    2024年02月09日
    浏览(33)
  • Java实现WebSocket客户端和服务端(简单版)

    天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。 写在前面: WebSocket是一种在单个TCP连接上进行全双工通信的协议。 WebSocket通信协议于

    2024年02月08日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包