使用spring boot +WebSocket的那些坑


springboot和websocket通訊時的坑有一個:下面這個東西要有


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


/**
 * Created with IntelliJ IDEA.
 *
 * @author: xincheng.zhao
 * @date: 2018/9/4
 * @description:
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter  serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}


spring里面還有創建下面的:

@ServerEndpoint(value = "/websocket")
@Component
public class WSController {
    //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
    private static int onlineCount = 0;
    //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<WSController> webSocketSet = new CopyOnWriteArraySet<WSController>();

    //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private Session session;

    /**
     * 連接建立成功調用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        System.out.println("有新連接加入!當前在線人數為");
    }
//
//    	//連接打開時執行
//    	@OnOpen
//    	public void onOpen(@PathParam("user") String user, Session session) {
//    		currentUser = user;
//    		System.out.println("Connected ... " + session.getId());
//    	}

    /**
     * 連接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        System.out.println("websocket close");
    }
    /*
     *收到客戶端消息
     */
    @OnMessage
    public  void onMessage(String message ,Session session){
        System.out.println("收到客戶端的消息:"+message);
    }

}

js里面實現:

  layim.on("sendMessage",function (res) {
        ws.send(JSON.stringify({
            type:"chatMessage",
            data:res
        }))
        layer.msg("發送消息成功")
    })

其他要配置好


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM