首页 > 其他分享 >springboot+websocket

springboot+websocket

时间:2022-09-28 10:01:28浏览次数:44  
标签:websocket springboot void webSocketSet session message public String


springboot+websocket

先引入websocket的依赖包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

html:

springboot+websocket_客户端

java:

1.先将服务器和浏览器建立连接

import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/socket")
public class WebSocketUtil {
// 创建一个线程安全的set集合用来存放每个客户端对应的WebSocketUtil
private CopyOnWriteArraySet<WebSocketUtil> webSocketSet = new CopyOnWriteArraySet<WebSocketUtil>();
// 与某个客户端的连接会话,通过它来给客户端发送消息
private Session session;

@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
System.out.println("你有新的连接");
}

@OnClose
public void onClose() {
webSocketSet.remove(this);
}

@OnError
public void one rror(Throwable e) {
System.out.println("发生了未知错误,服务终止");
e.printStackTrace();
}

@OnMessage
public void onMessage(String message) {
System.out.println("来自客户端的消息:"+message);
}

/**
* 发送单条数据
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
//getbasicRemote().sendText(message):同时发送信息
}

public void sendAll(String message) {
for(WebSocketUtil conn: webSocketSet) {
try {
conn.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {

}
}
2.创建ServerEndpointExporter来管理@ServerEndpoint注解生成的对象
----次配置必须要有,否则报404
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}

 

标签:websocket,springboot,void,webSocketSet,session,message,public,String
From: https://blog.51cto.com/u_15765446/5718402

相关文章