本文(2019年6月18日 飛快的蝸牛博客)
有許多人走着走着,就迷失了自己,所以不論發生了什么,有時候抱着自己去靜下來想想,要好好的對待自己;“錢塘江上潮信來,今日方知我是我”,我信奉這句話,不是我超脫了,是有時我們醒悟了;
注意標題:springboot使用websocket
1】第一步:引入依賴:
<!--集成websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2】第二步:配置websocket
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
*
* 使用@SpringBootApplication啟動類進行啟動時需要下面這段代碼,****但生成war包部署在tomcat中不需要這段
* 若打成war包使用tomcat運行的話,則注釋掉這個類中serverEndpointExporter 方法.
*
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3】第三步:可以在controller 下寫下此類:
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
* 即時通訊
*/
@Component
@ServerEndpoint("/webSocket")
public class MyWebScoketController {
private static int onlineCount = 0;
private static CopyOnWriteArraySet<MyWebScoketController> webSocketSet = new CopyOnWriteArraySet<MyWebScoketController>();
private Session session;
/**
* 連接建立成功調用的方法
* @param session 可選的參數。session為與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
System.out.println("有新連接加入!當前在線人數為" + getOnlineCount());
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose(){
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
System.out.println("有一連接關閉!當前在線人數為" + getOnlineCount());
}
/**
* 收到客戶端消息后調用的方法
* @param message 客戶端發送過來的消息
* @param session 可選的參數
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
//群發消息
for(MyWebScoketController item: webSocketSet){
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
@OnError
public void onError(Session session, Throwable error){
System.out.println("發生錯誤");
error.printStackTrace();
}
/**
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebScoketController.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebScoketController.onlineCount--;
}
}
4】第四步:在前端寫個公共myWebsocket.js 如下
if("WebSocket" in window){
console.log("this browser supports websocket...");
var webSocket=new WebSocket("ws://"+window.location.host+"/XXXX/webSocket");
}else{
console.log("this browser does not supports websocket...");
}
webSocket.onerror=function(){
console.log("鏈接錯誤...");
}
webSocket.onopen=function(){
console.log("鏈接成功...");
}
/*
* 哪個頁面使用哪個頁面加
* webSocket.onmessage=function(event){
alert(event);
}*/
webSocket.onclose=function(){
console.log("鏈接關閉...");
}
window.onbeforeunload=function(){
console.log("窗口即將關閉,准備關閉鏈接...");
webSocket.close();
}
function webSend(){
webSocket.send(decodeURIComponent($("#form1").serialize(),true));
}
function SendMesaage(mes){
webSocket.send(mes);
}
var closeConn=function(){
webSocket.close();
}
5】第五步:測試 現在頁面引入
<script type="text/javascript" src="static/js/common/myWebSocket.js"></script>
在發送消息端寫下:
SendMesaage(1300);
接收端寫下:
webSocket.onmessage=function(event){
此處可以接收到消息
}
如果對你有用,覺得好可以給小編打個賞: