SpringBoot——使用WebSocket功能
创始人
2024-05-30 17:09:47
0

springboot自带websocket,通过几个简单的注解就可以实现websocket的功能;

启动类跟普通的springboot一样:

/*** 2023年3月2日下午4:16:57*/
package testspringboot.test7websocket;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;/*** @author XWF**/
@SpringBootApplication
@PropertySource(value = "test7.properties")
public class Test7Main {/*** @param args*/public static void main(String[] args) {SpringApplication.run(Test7Main.class, args);}}

还需要一个websocket的配置类:

/*** 2023年3月2日下午4:26:15*/
package testspringboot.test7websocket;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** @author XWF**/
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

配置文件里只配置了一个端口:

主要的逻辑都放到@ServerEndpoint标签注释的类里,类似controller的功能;

可以使用4种注解处理业务:

  • @OnOpen:处理客户端的连接;
  • @OnClose:处理客户端断开;
  • @OnError:处理故障错误;
  • @OnMessage:处理具体消息,有三种消息类型:String类型,ByteBuffer类型,PongMessage类型,同一消息类型类里不能出现多次;

另外可以通过Session对象设置属性或者发送数据,session.getUserProperties()存取属性,session.getBasicRemote()或者session.getAsyncRemote()可以进行同步异步发送数据;

处理类:

/*** 2023年3月2日下午4:27:01*/
package testspringboot.test7websocket;import java.io.IOException;
import java.nio.ByteBuffer;import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;import org.springframework.stereotype.Component;/*** @author XWF**/
@Component
@ServerEndpoint(value = "/websockettest/{name}")
public class WebSocketHandler {@OnOpen  public void onOpen(@PathParam("name") String name, Session session) throws IOException {  System.out.println("onOpen:" + name);session.getUserProperties().put("name", name);}@OnClose  public void onClose(@PathParam("name") String name, Session session) throws IOException {System.out.println("onClose:" + name);System.out.println(session.getUserProperties().get("name") + "关闭了");}@OnError  public void onError(Session session, Throwable error) {System.out.println("onERROR");error.printStackTrace();  }@OnMessagepublic void textMessage(Session session, String msg) {System.out.println("收到:" + msg);try {session.getBasicRemote().sendText("hello");} catch (IOException e) {e.printStackTrace();}}@OnMessagepublic void binaryMessage(Session session, ByteBuffer msg) {System.out.println("Binary message: " + msg.toString());}@OnMessagepublic void pongMessage(Session session, PongMessage msg) {System.out.println("Pong message: " + msg.getApplicationData().toString());}}

测试websocket用的Apipost:

连接测试:

发送数据测试:

断开连接:

另外,也可以设置自己的编解码处理自己的消息,实现javax.websocket.Encoder.Text或者javax.websocket.Encoder.Binary接口实现编码器,实现javax.websocket.Decoder.Text或者javax.websocket.Decoder.Binary接口实现解码器,解码器最多两个,一个解码Text一个Binary;

在@ServerEndpoint注解里配置上自己的encoders和decoders就可以实现自定义编解码了;

自定义消息MsgA:

/*** 2023年3月3日下午3:12:47*/
package testspringboot.test7websocket;/*** @author XWF**/
public class MsgA {public int id;public String name;@Overridepublic String toString() {return "MsgA [id=" + id + ", name=" + name + "]";}}

编码器:

/*** 2023年3月3日下午3:14:02*/
package testspringboot.test7websocket;import javax.websocket.EncodeException;
import javax.websocket.Encoder.Text;
import javax.websocket.EndpointConfig;/*** @author XWF**/
public class MsgATextEncoder implements Text{@Overridepublic void init(EndpointConfig endpointConfig) {System.out.println("msga encoder init");}@Overridepublic void destroy() {System.out.println("msga encoder destroy");}// 进行编码操作,将对象编码成string@Overridepublic String encode(MsgA object) throws EncodeException {return object.toString();}}

解码器:

/*** 2023年3月3日下午3:16:52*/
package testspringboot.test7websocket;import javax.websocket.DecodeException;
import javax.websocket.Decoder.Text;
import javax.websocket.EndpointConfig;/*** @author XWF**/
public class MsgATextDecoder implements Text {@Overridepublic void init(EndpointConfig endpointConfig) {System.out.println("msga decoder init");}@Overridepublic void destroy() {System.out.println("msga decoder destroy");}// 进行解码操作,将string解码成需要的对象@Overridepublic MsgA decode(String s) throws DecodeException {MsgA msga = new MsgA();msga.id = Integer.parseInt(s.split(",")[0]);msga.name = s.split(",")[1];return msga;}// 验证消息是否可以解码,返回true可以解码,否则返回false@Overridepublic boolean willDecode(String s) {// 接收格式:id,nameif (s.split(",").length == 2) {try {Integer.parseInt(s.split(",")[0]);} catch (NumberFormatException e) {return false;}return true;} else {return false;}}}

处理类:

/*** 2023年3月3日下午3:07:45*/
package testspringboot.test7websocket;import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;import org.springframework.stereotype.Component;/*** @author XWF**/
@Component
@ServerEndpoint(value = "/websocketmsgtest", encoders = {MsgATextEncoder.class}, decoders = {MsgATextDecoder.class})
public class WebSocketMsgHandler {@OnOpenpublic void onOpen() {}@OnClosepublic void onClose() {}@OnErrorpublic void onError(Throwable error) {}@OnMessagepublic void textMessageA(Session session, MsgA msga) {System.out.println("收到:" + msga);MsgA sendMsg = new MsgA();sendMsg.id = 9999;sendMsg.name = "HELLO WORLD";try {session.getBasicRemote().sendObject(sendMsg);} catch (IOException e) {e.printStackTrace();} catch (EncodeException e) {e.printStackTrace();}sendMsg.id = 8888;sendMsg.name = "hello world";Future future = session.getAsyncRemote().sendObject(sendMsg);try {future.get(3, TimeUnit.SECONDS);System.out.println("发送完毕");} catch (InterruptedException | ExecutionException | TimeoutException e) {System.out.println("超时");e.printStackTrace();}}}

测试:

不按照解码格式要求请求会异常并断开连接:

正常测试:

相关内容

热门资讯

diy主机安卓系统推荐 亲爱的DIY爱好者们,你是否曾梦想过拥有一台完全由自己组装的安卓主机?想象一台运行流畅、功能强大的安...
安卓13系统可以安装吗 你有没有听说安卓13系统已经发布了?是不是迫不及待想要升级你的手机,体验一下新系统的魅力呢?不过,在...
手机壳平价推荐安卓系统,时尚与... 手机壳可是咱们手机的最佳守护者呢!想象你的宝贝手机在日常生活中难免会遭遇各种“小意外”,有了手机壳,...
麦芒是安卓系统吗,深度解析安卓... 你有没有想过,手机里的那个麦芒,它是不是安卓系统呢?这个问题,估计不少手机控都好奇过吧!今天,就让我...
苹果x系统感觉像安卓,安卓风潮... 你有没有发现,最近苹果的X系统好像有点儿像安卓呢?是不是觉得苹果的“高贵”形象突然变得有点儿接地气了...
小米的安卓系统设置在哪,轻松生... 你有没有发现,小米手机的操作界面简洁又美观,功能强大到让人爱不释手?但是,有时候你可能会觉得,这个设...
安卓系统荣耀排第一,引领智能手... 你知道吗?在智能手机的世界里,有一个系统可是风头无两,那就是安卓系统!而在这众多安卓手机品牌中,有一...
充电宝带安卓系统,便携式智能电... 你有没有想过,你的充电宝也能拥有自己的操作系统呢?没错,就是安卓系统!听起来是不是很酷?想象你的充电...
安卓类原生系统手机推荐,精选原... 你有没有想过,拥有一部安卓类原生系统手机,就像是拥有了掌控自己世界的魔法棒?没错,原生系统带来的流畅...
努比亚安卓13系统下载,下载与... 你有没有听说?努比亚手机最近可是大动作连连呢!他们推出了全新的安卓13系统,而且现在就可以下载啦!是...
一加5系统安卓10,安卓10系... 你有没有注意到,你的手机最近是不是变得特别聪明了?没错,我要说的就是那款让人眼前一亮的一加5手机,它...
ios系统数据转到安卓,iOS... 你是不是也有过这样的经历?手里拿着一台运行着iOS系统的苹果手机,突然有一天,你发现安卓手机的世界也...
安卓系统用什么修图,基于安卓系... 手机里的照片总是不够完美?别急,今天就来给你揭秘,安卓系统上那些超好用的修图神器!无论是磨皮美颜,还...
安卓使用低系统的软件 你有没有发现,手机里的那些老古董安卓系统,竟然还能玩出新花样?没错,就是那些使用低系统版本的安卓手机...
安卓系统怎么开通漫游,安卓系统... 你有没有遇到过这种情况:出国旅行,满心欢喜地想要用手机拍下那些美丽的风景,结果却发现信号全无,只能干...
编曲用软件推荐安卓系统,打造个... 音乐爱好者们,是不是在为编曲软件发愁呢?别急,今天就来给你推荐几款适合安卓系统的编曲神器,让你的音乐...
安卓系统版本更新后黑屏,安卓系... 最近是不是你也遇到了安卓系统更新后黑屏的尴尬情况?这可真是让人头疼啊!手机屏幕突然变成了一片漆黑,啥...
国家企业公示系统安卓app 你有没有发现,现在的生活越来越离不开手机了?无论是工作还是生活,手机都能帮我们解决不少麻烦。今天,我...
安卓系统更新提示失败,揭秘原因... 最近你的安卓手机是不是也遇到了更新提示失败的小麻烦?别急,让我来给你详细说说这个让人头疼的问题,让你...
ops电脑装安卓系统,开启多系... 你有没有想过,你的电脑装上安卓系统会是怎样的场景呢?想象你那台曾经只用来处理文档和浏览网页的电脑,突...