专门做外卖的网站,潍坊优化网站排名,咸阳网站建设,wordpress+支付宝+微信一、引言
小编最近一直在使用springboot框架开发项目#xff0c;毕竟现在很多公司都在采用此框架#xff0c;之后小编也会陆续写关于springboot开发常用功能的文章。
什么场景下会要使用到websocket的呢#xff1f;
websocket主要功能就是实现网络通讯#xff0c;比如说…一、引言
小编最近一直在使用springboot框架开发项目毕竟现在很多公司都在采用此框架之后小编也会陆续写关于springboot开发常用功能的文章。
什么场景下会要使用到websocket的呢
websocket主要功能就是实现网络通讯比如说最经典的客服聊天窗口、您有新的消息通知或者是项目与项目之间的通讯都可以采用websocket来实现。
二、websocket介绍
百度百科介绍WebSokcet
在公司实际使用websocket开发一般来都是这样的架构首先websocket服务端是一个单独的项目其他需要通讯的项目都是以客户端来连接由服务端控制消息的发送方式(群发、指定发送)。 但是也会有服务端、客户端在同一个项目当中具体看项目怎么使用。
本文呢采用的是服务端与客户端分离来实现包括使用springboot搭建websokcet服务端、html5客户端、springboot后台客户端 具体看下面代码。
三、服务端实现
步骤一 springboot底层帮我们自动配置了websokcet引入maven依赖
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-websocket/artifactId
/dependency步骤二如果是你采用springboot内置容器启动项目的则需要配置一个Bean。如果是采用外部的容器则可以不需要配置。
/*** 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;/*** Description: websocket 服务类*//**** ServerEndpoint 这个注解有什么作用** 这个注解用于标识作用在类上它的主要功能是把当前类标识成一个WebSocket的服务端* 注解的值用户客户端连接访问的URL地址**/Slf4j
Component
ServerEndpoint(/websocket/{name})
public class WebSocket {/*** 与某个客户端的连接对话需要通过它来给客户端发送消息*/private Session session;/*** 标识当前连接客户端的用户名*/private String name;/*** 用于存所有的连接服务的客户端这个对象存储是安全的*/private static ConcurrentHashMapString,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作为客户端--
dependencygroupIdorg.java-websocket/groupIdartifactIdJava-WebSocket/artifactIdversion1.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 {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;/*** Description: websocket 接口*/
public interface WebSocketService {/*** 群发* param message*/void groupSending(String message);/*** 指定发送* param name* param message*/void appointSending(String name,String 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;/*** Description:*/
public class TestMain {/*** 用于存所有的连接服务的客户端这个对象存储是安全的*/private static ConcurrentHashMapString, 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;}
}