websocket(一)--原生websocket使用

websocket(一)–原生websocket使用

一、简介

websocket可以在单tcp连接上进行全双工通信协议,即是服务端和客户端间可双向通信。这里对原生的websocket
使用进行示例介绍(需要新版浏览器支持)。

二、java端关键点

2.1 ServerEndpointExporter

ServerEndpointExporter,即org.springframework.web.socket.server.standard.ServerEndpointExporter,用于检测和注册以@ServerEndpoint注解的websocket endpoints。

2.2 Session

Session,即javax.websocket.Session,会话类,记录会话相关信息。

2.3 @ServerEndpoint

注解在类上,配置websocket endpoints,设置websocket连接地址。

2.4 处理方法

在endpoints类中,使用注解在方法,对连接过程进行处理。

  • @OnOpen:websocket连接时处理器;
  • @OnMessage:消息处理;
  • @OnError:连接出错处理;
  • @OnClose:连接失败处理;

三、前端关键点

3.1 websocket地址

以ws或wss开头,如:

var url = "ws://localhost:8080/talk_websocket/"
3.2 创建连接

使用WebSocket对象创建连接,如:

var webSocket = new WebSocket(url);
3.3 处理方法
  • webSocket.onopen:连接建立;
  • webSocket.onmessage:接收消息;
  • webSocket.onerror: 连接出错;
  • webSocket.onclose: 关闭连接;

四、 使用示例

这里使用spring boot,以聊天室为例进行示例。

4.1 添加maven依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
4.2 生成spring boot 启动类
package com.dragon.websocket_study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketStudyApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(WebsocketStudyApplication.class, args);
    }
}
4.3 定义spring web mvc配置类
package com.dragon.websocket_study.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
   
    /
     * 检测和注册endpoints
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
   
        return new ServerEndpointExporter();
    }<
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值