公司在做平台搭建,需要一个websocket的基础应用,由于websocket的实际业务场景多且复杂,所以并没有真的抽象出来一个底层的demo,只是做了一个比较基础的案例,适合初学者参考,并且标记了一些坑,是很多网上案例的bug。亲测成功的,希望对大家有帮助啦!
环境配置
1.首先介绍一下我的环境配置:windows7,jdk1.8,tomcat8.0.3,maven3.6,编辑器Idea
2.我用的框架是springboot2.0,所以对于websocket支持直接添加maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
3.由于tomcat8是自带websocket包,所以我们只能引入一种,否则会jar包冲突
核心代码
1.websocket配置类,启动websocket服务,注解千万别丢了,否则就是无效的
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.服务类,因为websocket采用的是ws协议,所以实现类就相当于我们的controller层,这里需要用到两个注解,分别是:@ServerEndpoint和@Component。
@ServerEndpoint("/ws/{sid}")
@Component
public class SocketServer {
private static int onlineCount = 0;
private static Map<Strin