程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Springboot 基础5 - websocket技术

发布于2021-05-29 23:33     阅读(1069)     评论(0)     点赞(9)     收藏(1)


websocket 协议?

Websocket 协议是HTM5 协议,它的出现解决了客户端发起多个http 请求到服务器的资源浏览器必须经过长时间的轮询问题而产生的,websocket 实现了多路复用,全双工通信方式,该协议可以实现客户端和浏览器端同时发送数据。

websocket 与 http 协议的不同之处?

http 是超文本传输协议,是一个简单的请求-响应协议,通常运行在Tcp 之上。该协议是应用层协议,基于B/S 架构的通信协议。且该协议是一种无状态协议,即服务器不保留与客户端的交易的任何状态。HTTP 是一种面向连接的协议,允许传递任意类型的数据对象。

典型的HTTP 事物处理过程如下:

(1)客户端与服务器建立连接

(2)客户向服务器提出请求

(3)服务器接收请求,并根据请求返回相应的文件,作为应答。

(4)客户端与服务器关闭连接

下表中展示了websocket 协议与http协议的不同之处:

区别httpwebsocket
连接方式http1.0 即普通的http请求,一般是短连接,一次请求,三次握手,完毕之后立即断开websocket 是http 协议的升级,http1.1 默认是长连接方式,长连接代表:一次连接,在一定期限内保持连接,保持tcp不断开,双方都可以即时通讯,是一种全双工通讯协议
场景http协议更适合普通文件请求,不适合即时通讯,一般我们要得到及时信息,通过http方式,我们就需要不断轮询,网络资源消耗大websocket 更适合做即时通讯,不需要不断的轮询,一次连接,长时间有效。

 

代码实现

基于maven 构建项目工具实现:

pom.xml 导入依赖

在pom.xml 中导入 websocket 依赖,如下所示:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-websocket </artifactId>
  4. </dependency>

编写websocketConfig 类

  1. @Configuration
  2. public class WebSocketConfig{
  3.  /**
  4.  * @return
  5.  */
  6.  @Bean
  7.  public ServerEndpointExporter serverEndpointExporter()   {
  8.    
  9.    return new ServerEndpointExporter();
  10. }
  11. }

实现WebSocket 协议类

  1. @ServerEndpoint("/websocket/{id}")
  2. @Component
  3. public class WebSockerServer{
  4.  
  5.  // session 会话集合
  6.  private static ConcurrentHashMap<String, Session> map = new ConcurrentHashMap<String, Session>();
  7.  
  8.  // 当前会话
  9.  private Session session;
  10.  // id
  11.  private String id = "";
  12.  
  13.  /**
  14.  * 连接,打开会话
  15.  *
  16.  * @param session 服务器端与客户端建立连接,生成数据
  17.  * @param id 客户端的唯一id
  18.  */
  19.  @OnOpen
  20.  public void onOpen(Seesion session, @PathParam("id") String id){
  21.    
  22.    this.session = session;
  23.    this.id = id;
  24.    // 加入到map 集合中
  25.    this.map.put(this.sid, this.session);
  26. }
  27.  
  28.  /**
  29.  * 关闭当前会话
  30.  */
  31.  @OnClose
  32.  public void onClose(){
  33.    try{
  34.      // 从名单中清除
  35.      this.map.remvoe(this.sid);
  36.      // 关闭会话
  37.      this.session.close();
  38.   } catch(IOException e){
  39.      // TODO Auto-generated catch block
  40.      e.printStackTrace()
  41.   }
  42. }
  43.  
  44.  /**
  45.  * 接受信息
  46.  *
  47.  * @param message 接收到信息
  48.  */
  49.  @OnMessage
  50.  public void onMessage(String message){
  51.    try{
  52.      System.out.println("message:" + message);
  53.      
  54.      // 广播数据
  55.      for(Entry<String, Session> entry: map.entrySet()){
  56.        entry.getValue().getBasicRemote().sendText(message);
  57.     }
  58.   }catch(Exception e){
  59.      e.printStackTrace();
  60.   }
  61. }
  62.  
  63.  /**
  64.  * 发送数据
  65.  *
  66.  * @param message 需要发送数据
  67.  */
  68.  public void sendMessage(String message){
  69.    try{
  70.      this.session.getBasicRemote().sendText(message);
  71.   }catch(Exception e){
  72.      e.printStackTrace();
  73.   }
  74. }
  75. }

前端界面

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
  8. <title>Bootstrap 101 Template</title>
  9. <link rel="stylesheet" type="text/css" href="../css/bootstrap.css" />
  10. <script src="../js/Vue2.6.11.js" type="text/javascript" charset="utf-8"></script>
  11. </head>
  12. <body>
  13. <div id="app">
  14. <div class="container">
  15. <form action="" method="">
  16. <div class="row">
  17. <div class="form-group col-md-6">
  18. <label>信息展示:</label>
  19. <textarea class="form-control" rows="10" cols="" v-model="showContent"></textarea>
  20. </div>
  21. <div class="col-md-6">
  22. <div class="row">
  23. <div class="form-group col-md-12">
  24. <label>发送人ID:</label>
  25. <input type="text" class="form-control" name="" v-model="id" />
  26. </div>
  27. </div>
  28. <div class="row">
  29. <div class="form-group col-md-12">
  30. <label>发送信息:</label>
  31. <textarea class="form-control" rows="6" cols="" v-model="sendContent"></textarea>
  32. </div>
  33. </div>
  34. <div class="row">
  35. <div class="form-group col-md-6">
  36. <button type="button" class="btn btn-primary btn-block" @click="sendMsg()">点击发送</button>
  37. </div>
  38. <div class="form-group col-md-6">
  39. <button type="button" class="btn btn-danger btn-block" @click="connect()">连接</button>
  40. </div>
  41. </div>
  42. </div>
  43. </div>
  44. </form>
  45. </div>
  46. </div>
  47. <script type="text/javascript">
  48. var vm = new Vue({
  49. el: '#app',
  50. data: {
  51. id: '',
  52. showContent: '',
  53. sendContent: '',
  54. socket: null
  55. },
  56. methods: {
  57. connect: function() {
  58. var lsocket;
  59. if (typeof(WebSocket) == "undefined") {
  60. console.log("您的浏览器不支持WebSocket,请更换浏览器");
  61. return;
  62. } else {
  63. console.log("您的浏览器支持WebSocket");
  64. if (this.id.trim() == "") {
  65. alert('连接之前必须指定唯一ID')
  66. return
  67. }
  68. lsocket = new WebSocket("ws://localhost:8080/websocket/" + this.id)
  69. this.socket = lsocket
  70. this.socket.onopen = function() {
  71. console.log('连接已开放')
  72. }
  73. this.socket.onerror = function() {
  74. alert('websocket出现error')
  75. }
  76. this.socket.onmessage = function(msg) {
  77. console.log(msg)
  78. vm.showContent += msg.data
  79. }
  80. }
  81. },
  82. sendMsg: function() {
  83. if(this.sendContent.trim()==""||this.socket==null)
  84. {
  85. alert('不能发送空的信息哦,发送信息前,要先连接')
  86. return
  87. }
  88. this.socket.send(this.sendContent)
  89. this.sendContent=''
  90. }
  91. },
  92. created: function() {
  93. }
  94. })
  95. </script>
  96. </body>
  97. </html>

 

启动类

  1. @SpringBootApplication
  2. public  class AppWebSocket{
  3.  
  4.  public static void main(String[] args){
  5.    SpringApplication.run(App.class, args);
  6. }
  7. }


所属网站分类: 技术文章 > 博客

作者:听说你没有见过我

链接:http://www.javaheidong.com/blog/article/207793/f50f4cf1a21571a6a5f7/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

9 0
收藏该文
已收藏

评论内容:(最多支持255个字符)