springBoot结合WebSocket实现通讯小Demo

springBoot结合WebSocket实现通讯小Demo

图片: 在这里插入图片描述
一、服务端

1.1 新建一个工程

取名为:spring-boot-websocket

1.2 引入依赖

在pom.xml文件中添加如下依赖:

org.springframework.boot
spring-boot-starter-websocket

/**spring-boot-starter-websocket中就会自动引入spring-boot-starter-web和spring-boot- */starter,所以我们就不需要引入了。

1.3 注入ServerEndpointExporter
编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint,代码如下:

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

1.4 websocket的具体实现类
websocket的代码:

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
 
    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new    CopyOnWriteArraySet<MyWebSocket>();
 
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
 
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
      
        webSocketSet.add(this);     //加入set中
        System.out.println("有新连接加入!当前在线人数为" + webSocketSet.size());
        this.session.getAsyncRemote().sendText("恭喜您成功连接上WebSocket-->当前在线人数为:"+webSocketSet.size());
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        System.out.println("有一连接关闭!当前在线人数为" + webSocketSet.size());
    }
 
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
 
        //群发消息
        broadcast(message);
    }
 
    /**
     * 发生错误时调用
     *
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
 
    /**
     * 群发自定义消息
     * */
    public  void broadcast(String message){
        for (MyWebSocket item : webSocketSet) {
               //同步异步说明参考:websocket getAsyncRemote()和getBasicRemote()区别
               //this.session.getBasicRemote().sendText(message);
               item.session.getAsyncRemote().sendText(message);//异步发送消息.
        }
    }
}

使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。

虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。

1.5 编写/访问控制

编写IndexController,可以访问地址/到index.html页面。

@Controller
public class IndexController {
       @RequestMapping("/")
       public String index(){
              return "index";
       }
}

1.6 编写启动类
@SpringBootApplication
public class App {
publicstaticvoid main(String[] args) {
SpringApplication.run(App.class, args);
System.out.println("--------------ok---------");
}
}
到这里服务的部分就编写完毕了,接下来就是客户端的代码了。
二、客户端

客户端的代码主要是放在index.html页面中,在页面中使用H5提供的WebSocket对象,具体如下代码(src/main/resources/templates/index.html):

連接
断开连接



消息: 发送

三、运行测试

(1)打开浏览器访问地址http://127.0.0.1:8080/

(2)点击【连接WebSocket】,然后就可以发送消息了。

(3)打开另外一个浏览器或者直接打开一个TAB访问地址http://127.0.0.1:8080/

(4)点击【连接WebSocket】,然后就可以发送消息了。

(5)观察两边的信息打印,看是否可以接收到消息。

这样就OK了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值