package com.pqs9300.controller.socket;


import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {

    private Session session;

    /*线程安全set 存放每个客户端处理消息的对象*/
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet();

    /*websocket 连接建立成功后进行调用*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
    }
    /*websocket 链接关闭调用的方法*/
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    /*收到客户端消息后调用的方法*/
    @OnMessage
    public void onMessage(String message) throws IOException {
        for (WebSocketServer socket : webSocketSet) {
            socket.session.getBasicRemote().sendText("自己嘎给自己嘎发的消息："+message);
        }
    }
    /*websocket 发生错误时进行调用*/
    @OnError
    public void onError(Throwable error){
        System.out.println("onError......"+error.getMessage());
    }
    public void sendMessage(String message) throws IOException {
        for (WebSocketServer socket : webSocketSet) {
            socket.session.getBasicRemote().sendText(message);
        }
    }
    public Session getSession() {
        return session;
    }
    public void setSession(Session session) {
        this.session = session;
    }
}
