1.去除项目websocket其他依赖,只引入springboot-websocket。当然也可以用websocket-netty
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 或者使用如下依赖 -->
<dependency>
<groupId>com.simon</groupId>
<artifactId>spring-boot-starter-websocket-netty</artifactId>
<version>0.0.1</version>
</dependency>
2.编写ws终端
import org.springframework.stereotype.Component;
import javax.websocket.*;
@Component
@ServerEndpoint(value="/websocket/{userId}")
public class LampWebsocketEndPoint {
private String userId;
//连接时执行
@SuppressWarnings("static-access")
@OnOpen
public void onOpen(@PathParam("userId") String userId,Session session) //throws IOException, LineUnavailableException
{
this.userId = userId;
System.out.println("新连接:{"+userId+"}");
}
//关闭时执行
@SuppressWarnings("static-access")
@OnClose
public void onClose(){
//logger.debug("连接:{} 关闭",this.userId);
System.out.println("连接:{"+this.userId+"} 关闭");
}
//收到消息时执行
@SuppressWarnings("static-access")
@OnMessage
public void onMessage(String message, Session session) throws IOException {
//logger.debug("用户{}收到的消息{}",this.userId,message);, InputStream inputStream
System.out.println(this.userId+"收到消息{"+message+"}");
}
/**
* @des 接收二进制消息
* @throws IOException
*/
@OnMessage
public void onMessage( @PathParam("userId") String userId, InputStream inputStream,Session session) //throws IOException
{
}
//连接错误时执行
@SuppressWarnings("static-access")
@OnError
public void onError(Session session, Throwable error){
//logger.debug("用户id为:{}的连接发送错误",this.userId);
System.out.println("用户id为:{"+this.userId+"}的连接发送错误");
error.printStackTrace();
}
}
3.必须配置ws支持组件,在spring配置文件中配置如下bean即可
@Bean("serverEndpointExporter")
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}