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

websocket基础

 

下面就以代码来进行说明

1,先导入websocket依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

2.编写websocket相关bean管理配置

@Configuration
public class config {//申明websocket是由bean管理的@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}

3.编写业务层代码

@ServerEndpoint("/api/{user_id}")
@Component
public class servlet {private  String id;//客户端建立@OnOpenpublic  void  onopen(Session  session,  @PathParam("user_id")String id){this.id=id;try {session.getBasicRemote().sendText("连接建立成功");} catch (IOException e) {throw new RuntimeException(e);}System.out.println("连接建立");}//客户端发送消息,服务端接受@OnMessagepublic  void  onoMessage(String  message,  Session session){System.out.println(message);try {//向客户端返还信息session.getBasicRemote().sendText("消息收到");} catch (IOException e) {throw new RuntimeException(e);}}//客户端关闭时候@OnClosepublic  void  onoClose(Session  session,  @PathParam("user_id")String id){this.id=id;System.out.println("连接关闭");}
}

注意@ServerEndpoint("/api/{user_id}")此注解供websocket提供访问连接url

4.附赠前端代码一份

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head><body>
<input id="input"  type="text" placeholder="输入你的内容">
<button id="but">发送请求</button>
<div id="div1" style="width: 200px;height: 200px; background:yellow;"></div>
<script>let input = document.getElementById("input");let but = document.getElementById("but");let div1 = document.getElementById("div1");//参数1:websocket服务地址var socket=new WebSocket("ws://localhost:8080/api/1");//open:当websocket服务连接成功socket.addEventListener("open",function (){div1.innerHTML="连接服务成功了"//客户端发送消息socket.send("发送成功")})//message:接受客户端的信息socket.addEventListener("message",function (re){console.log(re.data)})//客户端关闭时socket.addEventListener("close",function (){div1.innerHTML="我已经离开了"})
</script>
</body>
</html>

5.代码一些关键解析

http://www.lryc.cn/news/152053.html

相关文章:

  • 游戏思考30(补充版):关于逆水寒铁牢关副本、白石副本和技能的一些注释(2023/0902)
  • 【数据蒸馏】静态数据蒸馏方法汇总
  • Cortex-A7 架构
  • 2023年“羊城杯”网络安全大赛 Web方向题解wp 全
  • Matlab——二维绘图(最为详细,附上相关实例)
  • JVM学习(四)--内存问题分析思路
  • 【MySQL】七种SQL优化方式 你知道几条
  • MySQL8.xx 解决1251 client does not support ..解决方案
  • SpringBoot常用的简化开发注解
  • python相关
  • C语言的类型转换
  • 从零构建深度学习推理框架-11 Resnet
  • 多线程练习-顺序打印
  • 一文读懂MQTT各参数定义(非ChatGPT生成版)
  • redis-lua脚本-无参-比较2个数值
  • Lesson5-1:OpenCV视频操作---视频读写
  • Lesson5-2:OpenCV视频操作---视频追踪
  • 1778_树莓派系统安装
  • 关闭jenkins插件提醒信息
  • JixiPix Artista Impresso Pro for mac(油画滤镜效果软件)
  • 机器学习之 Jupyter Notebook 使用
  • Unity引擎修改模型顶点色的工具
  • linux安装minio以及springboot整合使用
  • javaee 事务 事务的特性 事务的并发问题 事务的隔离级别
  • Matlab怎么引入外部的latex包?Matlab怎么使用特殊字符?
  • day-07 I/O复用(select)
  • Glide的使用及源码分析
  • 外贸爬虫系统
  • CentOS 8 安装 Code Igniter 4
  • .net framework 提示安装了 但是删除面板看不到