一、引言

小编最近一直在使用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*/@Beanpublic 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<>();@OnOpenpublic 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());}@OnClosepublic void OnClose(){webSocketSet.remove(this.name);log.info("[WebSocket] 退出成功,当前连接人数为:={}",webSocketSet.size());}@OnMessagepublic 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 {@Beanpublic WebSocketClient webSocketClient() {try {WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8085/websocket/test"),new Draft_6455()) {@Overridepublic void onOpen(ServerHandshake handshakedata) {log.info("[websocket] 连接成功");}@Overridepublic void onMessage(String message) {log.info("[websocket] 收到消息={}",message);}@Overridepublic void onClose(int code, String reason, boolean remote) {log.info("[websocket] 退出连接");}@Overridepublic 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{@Autowiredprivate WebSocketClient webSocketClient;@Overridepublic void groupSending(String message) {// 这里我加了6666-- 是因为我在index.html页面中,要拆分用户编号和消息的标识,只是一个例子而已// 在index.html会随机生成用户编号,这里相当于模拟页面发送消息// 实际这样写就行了 webSocketClient.send(message)webSocketClient.send(message+"---6666");}@Overridepublic 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 {@Autowiredprivate 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值都是不同的,所以在这里没有出现对象改变而把之前对象改变的现象。

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

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

最后总结:这位小伙伴提出的观点确实是正确的,但是在实际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":"李四"}}

----------------------------------------------------- 更新于2019-08-14 -----------------------------------------------------

springboot+websocket实现服务端、客户端相关推荐

  1. ssm配置socket_ssm框架中集成websocket实现服务端主动向客户端发送消息

    找了很多配置文档及实例说明,也还是没能成功,最终在csdn博客中发现了基于stomp的消息推送的文章, 下面整理自csdn博客,https://blog.csdn.net/u013627689/art ...

  2. 使用HTML5的WebSocket实现服务端和客户端数据通信(有演示和源码)

    WebSocket协议是基于TCP的一种新的网络协议.WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术.依靠这种技术可以实现客户端和服务器端的长连接,双向实时通信. ...

  3. android java websocket client_websocket服务端,android客户端示例

    服务端库依赖详见章末 #####spring websocket服务端代码(会话过程) public class HandshakeInterceptor extends HttpSessionHan ...

  4. SpringBoot整合WebService(服务端+客户端)

    SpringBoot整合WebService(服务端+客户端) 文章目录 SpringBoot整合WebService(服务端+客户端) 一.服务端 1.项目结构 2.创建好SpringBoot项目后 ...

  5. SpringBoot+SOCKET服务端客户端

    springBoot启动socket服务端 socket服务端简单实现实例 springBoot启动socket服务端 SOCKET服务端启动 SOCKET客户端连接测试 模拟业务处理线程类 模拟监测 ...

  6. 除了 Websocket ,服务端还有什么办法能向浏览器主动推送信息?

    除了 Websocket ,服务端还有什么办法能向浏览器主动推送信息? 前言 端倪 Server-Sent Events 是什么? Server-Sent Events 与 Websocket 对比 ...

  7. react服务端/客户端,同构代码心得

    FKP-REST是一套全栈javascript框架 react服务端/客户端,同构代码心得 作者:webkixi react服务端/客户端,同构代码心得 服务端,客户端同构一套代码,大前端的梦想,为了 ...

  8. restful服务端客户端_测试RESTful服务的客户端

    restful服务端客户端 开发使用RESTful Web API的应用程序可能意味着开发服务器和客户端. 为服务器端编写集成测试可以像使用Arquillian启动服务器一样容易,并且可以通过REST ...

  9. TCP/IP网络编程之基于TCP的服务端/客户端(二)

    回声客户端问题 上一章TCP/IP网络编程之基于TCP的服务端/客户端(一)中,我们解释了回声客户端所存在的问题,那么单单是客户端的问题,服务端没有任何问题?是的,服务端没有问题,现在先让我们回顾下服 ...

最新文章

  1. c:#ifndef, #define, #endif 作用
  2. 【原创】erlang 模块之 epmd
  3. OutOfMemoryError:无法创建新的本机线程–问题神秘化
  4. php 和jsp,jsp和php哪个好?jsp和php的简单比较
  5. 代码智能技术如何应用到日常开发?
  6. Java 主流垃圾收集器
  7. C++设计模式-Singleton
  8. 蒋步星:轻量级大数据计算引擎
  9. python中json模块_Python json模块与jsonpath模块区别详解
  10. (8)Powershell中变量的定义和使用
  11. VLAN中tagged与untagged的处理(转)
  12. 台式计算机能不能安装蓝牙驱动,win7电脑蓝牙驱动怎么安装,详细教您怎么安装...
  13. 园林景观cad_景观广场及绿化设计(附CAD平面图)
  14. 多种矿石混合的抗干扰矿石对讲机
  15. Nginx自签名证书的配置
  16. mysql身份证来算年龄_MySQL 根据身份证出生年月计算年龄户籍地性别
  17. SiteGround主机和HostGator哪个好?(权威技术性分析)2022最新对比
  18. html+JavaScript 实现贪吃蛇程序
  19. 2021美食林全球餐厅精选榜公布,这里有一份美食地图请查收!
  20. 现代的linux和windows7,Windows 7 Vs. Linux谁更强

热门文章

  1. 身价首破2000亿美元!马斯克超贝索斯重登世界首富
  2. 数据库之文件管理--SimpleDB
  3. java上传图片限制大小_求高手解决用java限制上传图片大小!!
  4. Linux网络收音机
  5. 在某个下午,拉开折叠屏交互的时代大幕
  6. 华夏基金:基金行业数字化转型实践成果分享
  7. LeetCode-Algorithms-[Easy]LCP 02. 分式化简
  8. Error: Request failed with status code 403
  9. js获取父级html元素,js获取当前元素所有子级元素的(js获取父级元素下面的所有子元素)...
  10. 如何获取网页上的LOGO