websocket我这里就不解释了,直接开始怎么用吧。
首先引入springboot为我们提供好的jar包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>3.2.3</version>
</dependency>
然后编写配置类,扫描并添加有 @ServerEndpoint 注解的Bean。
package online.emilia.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
//配置websocket,用于学员考试
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
然后就可以创建websocket实例了。
package online.emilia.ws;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
@ServerEndpoint("/chat")
public class ExamWebSocket {
@OnOpen
public void onOpen(Session session){
//建立websocket连接后,会执行
}
@OnMessage
public void onMessage(String message){
}
@OnError
public void onError(Session session){
}
@OnClose
public void onClose(Session session){
}
}
这就是springboot下的基础使用全双工通信的方式。