package com.huimv.env.input.ws;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * websocket接口处理类
 */
@Component
@ServerEndpoint(value = "/smart/{token}")
public class WorkerController extends TextWebSocketHandler {


    @OnOpen
    public void onOpen(@PathParam(value = "token") Integer token, Session session) {
        // 添加到session的映射关系中
        WebsocketWorkerUtil.addSession(token, session);
    }

    /**
     * 连接事件，加入注解
     * 用户断开链接
     */
    @OnClose
    public void onClose(@PathParam(value = "token") Integer token, Session session) {
        // 删除映射关系
        WebsocketWorkerUtil.removeSession(token);
    }

    /**
     * 当接收到用户上传的消息
     */
    @OnMessage
    public void onMessage(@PathParam(value = "token") Integer token, Session session, String message) {
        String msg = "[" + token + "]:" + message;

        System.out.println("接收到信息：" + msg);
    }

    private void keepAlive(Session session) {
//        WebsocketSellerUtil.sendMessage(session,new WsEvent("pon",null));
    }

    /**
     * 处理用户活连接异常
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }
}
