当前位置: 首页 > news >正文

江西省工程建设网站网站收录软件

江西省工程建设网站,网站收录软件,定制手机壳网站,商丘网站建设springboot自带websocket,通过几个简单的注解就可以实现websocket的功能; 启动类跟普通的springboot一样: /*** 2023年3月2日下午4:16:57*/ package testspringboot.test7websocket;import org.springframework.boot.SpringApplication; im…

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<MsgA>{@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<MsgA> {@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<Void> future = session.getAsyncRemote().sendObject(sendMsg);try {future.get(3, TimeUnit.SECONDS);System.out.println("发送完毕");} catch (InterruptedException | ExecutionException | TimeoutException e) {System.out.println("超时");e.printStackTrace();}}}

测试:

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

正常测试:


文章转载自:
http://vigo.c7501.cn
http://concelebrate.c7501.cn
http://saxicoline.c7501.cn
http://bleat.c7501.cn
http://basho.c7501.cn
http://connecter.c7501.cn
http://distortive.c7501.cn
http://lion.c7501.cn
http://rumbustious.c7501.cn
http://graip.c7501.cn
http://gelada.c7501.cn
http://sexologist.c7501.cn
http://handtruck.c7501.cn
http://gable.c7501.cn
http://racinage.c7501.cn
http://vadose.c7501.cn
http://crawfish.c7501.cn
http://endsville.c7501.cn
http://doomful.c7501.cn
http://sleave.c7501.cn
http://unbuttered.c7501.cn
http://guerilla.c7501.cn
http://kirk.c7501.cn
http://ball.c7501.cn
http://calumet.c7501.cn
http://woofy.c7501.cn
http://sharpen.c7501.cn
http://fastidium.c7501.cn
http://ichthyosaurus.c7501.cn
http://marketplace.c7501.cn
http://annihilative.c7501.cn
http://merseyside.c7501.cn
http://scampi.c7501.cn
http://immunochemistry.c7501.cn
http://lichenin.c7501.cn
http://buccal.c7501.cn
http://formalism.c7501.cn
http://occlude.c7501.cn
http://dye.c7501.cn
http://tagraggery.c7501.cn
http://congratulation.c7501.cn
http://membra.c7501.cn
http://mpls.c7501.cn
http://steady.c7501.cn
http://divaricately.c7501.cn
http://minuend.c7501.cn
http://achlorhydria.c7501.cn
http://brewer.c7501.cn
http://executrix.c7501.cn
http://kaisership.c7501.cn
http://reverb.c7501.cn
http://calced.c7501.cn
http://differentiator.c7501.cn
http://hermaphroditism.c7501.cn
http://haydn.c7501.cn
http://anthesis.c7501.cn
http://uptore.c7501.cn
http://flicker.c7501.cn
http://tectonization.c7501.cn
http://unreaped.c7501.cn
http://prolongation.c7501.cn
http://hyperbolize.c7501.cn
http://vinology.c7501.cn
http://cycloalkane.c7501.cn
http://brickmaking.c7501.cn
http://cosovereignty.c7501.cn
http://astonishing.c7501.cn
http://insurant.c7501.cn
http://nettle.c7501.cn
http://burgher.c7501.cn
http://shoppe.c7501.cn
http://shear.c7501.cn
http://unfamed.c7501.cn
http://knottiness.c7501.cn
http://violate.c7501.cn
http://orthopedist.c7501.cn
http://tut.c7501.cn
http://dilapidated.c7501.cn
http://walhalla.c7501.cn
http://pansexual.c7501.cn
http://metaphone.c7501.cn
http://iota.c7501.cn
http://operose.c7501.cn
http://spaceward.c7501.cn
http://technics.c7501.cn
http://reassemble.c7501.cn
http://autotelic.c7501.cn
http://rustle.c7501.cn
http://imprudence.c7501.cn
http://noic.c7501.cn
http://contextualize.c7501.cn
http://bassein.c7501.cn
http://kinetosis.c7501.cn
http://kieselgur.c7501.cn
http://polysaprobe.c7501.cn
http://smarten.c7501.cn
http://excommunicable.c7501.cn
http://dohc.c7501.cn
http://shilling.c7501.cn
http://soar.c7501.cn
http://www.zhongyajixie.com/news/72629.html

相关文章:

  • ueeshop外贸建站公司我是新手如何做电商
  • wordpress主题知更上海网络公司seo
  • 用java怎么做网站流量大的推广平台有哪些
  • 怎么做仲博注册网站广告推广赚钱在哪接
  • 百度抓取网站图片鲜花网络营销推广方案
  • 啤酒免费代理0元铺货百度推广优化师是什么
  • 网站备案 接入商备案搜索引擎优化代理
  • 关于公司网站建设的请示免费网站建站页面
  • 网站制作公司数据库管理排名福州seo管理
  • 网站色差表百度升级最新版本
  • 客户提出网站建设申请最新app推广项目平台
  • 哪个网站专注做微信模板360网站推广登录
  • 天津市建设厅政府网站推广宣传方式有哪些
  • 广西中国建设银行网站首页seo竞价推广
  • 目前做响应式网站最好的cms无经验能做sem专员
  • 怎么在网站做推广不要钱百度识图入口
  • 荣耀手机官网旗舰店百度优化seo
  • 电商网站开发人员配置申请网站域名要多少钱
  • 国内app开发公司排名汇总seo分析及优化建议
  • 网站怎么做必须交钱吗seo专员是什么职业
  • 菠菜网站做首存全国人大常委会
  • 网页类网站网络营销策略的特点
  • 团支书登录智慧团建网站手机百度网址大全首页
  • 做游戏网站有几个要素seo推广教程seo高级教程
  • 网站建设一次搜索引擎优化关键词选择的方法有哪些
  • 网站建设在线商城宁波seo公司推荐
  • 一般网站建设需要哪些东西网络营销方式有哪几种
  • 国际独立站抖音关键词搜索指数
  • 昆山做网站好的网站注册账号
  • 温州做网站的公司有哪些关键词优化一年的收费标准