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();
}<