1. pom.xml引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 創(chuàng)建配置類:WebSocketConfig
@Configuration
@EnableCaching
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. 自定義配置類(為了保證websocket能夠像controller一樣使用):SpringContextHelper
// 自定義配置類
@Component
public class SpringContextHelper extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
// 通過手動注入applicationContext上下文獲取Bean
private static volatile BeanFactory context;
@Override
public <T> TgetEndpointInstance(Class<T> clazz) throws InstantiationException {
return context.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
SpringContextHelper.context = applicationContext;
}
}
4、創(chuàng)建websocket監(jiān)聽類:Web1
import com.alibaba.fastjson.JSON;
import com.epf.app.redis.SmsRedisService;
import com.epf.csce.config.SpringContextHelper;
import com.epf.csce.dao.BjMyCollectDao;
import com.epf.csce.dao.BjNewsTrendsDao;
import com.epf.csce.entity.BjMyCollectEntity;
import com.epf.csce.entity.BjNewsTrendsEntity;
import com.epf.csce.entity.WxSocketEntity;
import com.epf.csce.service.BjPopularRecommendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value= "/wxsmall/web1", configurator= SpringContextHelper.class)
@Component
public class Web1 {
private static Logger log = LoggerFactory.getLogger(Web1.class);
//靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的MyWebSocket對象。
private static CopyOnWriteArraySet<Web1> webSocketSet = new CopyOnWriteArraySet<Web1>();
//與某個客戶端的連接會話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
private Session session;
@Autowired
private SmsRedisService redisService;
@Autowired
private BjPopularRecommendService bjPopularRecommendService;
@Resource
private BjMyCollectDao bjMyCollectDao;
@Resource
private BjNewsTrendsDao bjNewsTrendsDao;
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數(shù)加1
log.info("有新連接加入!當(dāng)前在線人數(shù)為" + getOnlineCount());
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("websocket IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減1
log.info("有一連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
* @parammessage 客戶端發(fā)送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("來自客戶端的消息:" + message);
//群發(fā)消息
for (Web1 item: webSocketSet) {
String result= "";
try {
item.sendMessage(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @paramsession
* @paramerror
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發(fā)生錯誤");
error.printStackTrace();
}
/**
* 服務(wù)器主動推送
* @parammessage
* @throwsIOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群發(fā)自定義消息
*/
public static void sendInfo(String message) throws IOException {
log.info(message);
for (Web1 item: webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
Web1.onlineCount++;
}
public static synchronized void subOnlineCount() {
Web1.onlineCount--;
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。