服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - springboot websocket简单入门示例

springboot websocket简单入门示例

2021-05-25 13:03王强劲 Java教程

这篇文章主要介绍了springboot websocket简单入门示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

之前做的需求都是客户端请求服务器响应,新需求是服务器主动推送信息到客户端.百度之后有流、长轮询、websoket等方式进行.但是目前更加推崇且合理的显然是websocket.

springboot官网翻译了一些资料,再加上百度简单实现了springboot使用websocekt与客户端的双工通信.

1.首先搭建一个简单的springboot环境

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- inherit defaults from spring boot -->
  <parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.0.4.release</version>
  </parent>
 
  <!-- add typical dependencies for a web application -->
  <dependencies>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
  </dependencies>

2.引入springboot整合websocket依赖

?
1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-websocket</artifactid>
  <version>2.0.4.release</version>
</dependency>

3.创建启动springboot的核心类

?
1
2
3
4
5
6
7
8
9
10
11
package com;
 
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
 
@springbootapplication
public class globalconfig {
  public static void main(string[] args) {
    springapplication.run(globalconfig.class, args);
  }
}

4.创建websocket服务器

正如springboot 官网推荐的websocket案例,需要实现websockethandler或者继承textwebsockethandler/binarywebsockethandler当中的任意一个.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.xiaoer.handler;
 
import com.alibaba.fastjson.jsonobject;
import org.springframework.web.socket.textmessage;
import org.springframework.web.socket.websocketsession;
import org.springframework.web.socket.handler.textwebsockethandler;
 
import java.util.hashmap;
import java.util.map;
 
/**
 * 相当于controller的处理器
 */
public class myhandler extends textwebsockethandler {
  @override
  protected void handletextmessage(websocketsession session, textmessage message) throws exception {
    string payload = message.getpayload();
    map<string, string> map = jsonobject.parseobject(payload, hashmap.class);
    system.out.println("=====接受到的数据"+map);
    session.sendmessage(new textmessage("服务器返回收到的信息," + payload));
  }
}

5.注册处理器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.xiaoer.config;
 
import com.xiaoer.handler.myhandler;
import org.springframework.context.annotation.configuration;
import org.springframework.web.socket.websockethandler;
import org.springframework.web.socket.config.annotation.enablewebsocket;
import org.springframework.web.socket.config.annotation.websocketconfigurer;
import org.springframework.web.socket.config.annotation.websockethandlerregistry;
 
@configuration
@enablewebsocket
public class websocketconfig implements websocketconfigurer {
  @override
  public void registerwebsockethandlers(websockethandlerregistry registry) {
    registry.addhandler(myhandler(), "myhandler/{id}");
  }
  public websockethandler myhandler() {
    return new myhandler();
  }
 
}

6.运行访问

springboot websocket简单入门示例

出现如上图是因为不能直接通过http协议访问,需要通过html5的ws://协议进行访问.

7.创建html5 客户端

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
  </head>
  <body>
    <input id="text" type="text" />
    <button onclick="send()">send</button> 
    <button onclick="closewebsocket()">close</button>
    <div id="message">
    </div>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
      
      var userid="888";
      var websocket=null;
 
      $(function(){
        connectwebsocket();
      })
      
      //建立websocket连接
      function connectwebsocket(){
 
        console.log("开始...");
       
       //建立websocket连接
        websocket = new websocket("ws://127.0.0.1:8080/myhandler/id="+userid);
       
       //打开websokcet连接时,回调该函数
        websocket.onopen = function () {  
          console.log("onpen");
        }
        
        //关闭websocket连接时,回调该函数
        websocket.onclose = function () {
        //关闭连接 
          console.log("onclose");
        }
 
        //接收信息
        websocket.onmessage = function (msg) {
          console.log(msg.data);
        }
 
      }
      //发送消息
      function send(){
        var postvalue={};
        postvalue.id=userid;
        postvalue.message=$("#text").val();    
        websocket.send(json.stringify(postvalue));
      }
      //关闭连接
      function closewebsocket(){
        if(websocket != null) {
          websocket.close();
        }
      }
    </script>
  </body>
</html>

8.运行

springboot websocket简单入门示例

利用客户端运行之后仍然会出现上图中的一连接就中断了websocket连接.

这是因为spring默认不接受跨域访问:

as of spring framework 4.1.5, the default behavior for websocket and sockjs is to accept only same origin requests.

需要在websocketconfig中设置setallowedorigins.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.xiaoer.config;
 
import com.xiaoer.handler.myhandler;
import org.springframework.context.annotation.configuration;
import org.springframework.web.socket.websockethandler;
import org.springframework.web.socket.config.annotation.enablewebsocket;
import org.springframework.web.socket.config.annotation.websocketconfigurer;
import org.springframework.web.socket.config.annotation.websockethandlerregistry;
 
@configuration
@enablewebsocket
public class websocketconfig implements websocketconfigurer {
  @override
  public void registerwebsockethandlers(websockethandlerregistry registry) {
    registry.addhandler(myhandler(), "myhandler/{id}")
      .setallowedorigins("*");
  }
  public websockethandler myhandler() {
    return new myhandler();
  }
 
}

如下图,并未输出中断,说明连接成功.

springboot websocket简单入门示例

9.服务器和客户端的相互通信

服务器端收到消息

springboot websocket简单入门示例

客户端收到服务器主动推送消息

springboot websocket简单入门示例

以上就是一个最基础的springboot简单应用.还可以通过拦截器、重写websocketconfigurer中的方法进行更为复杂的属性操作.具体可以参考springboot集成websocket【基于纯h5】进行点对点[一对一]和广播[一对多]实时推送

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000016012270

延伸 · 阅读

精彩推荐