LogWebsockController.java 2.1 KB
package com.tianbo.warehouse.controller;

import com.tianbo.warehouse.handle.IO_Log_Handle;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CopyOnWriteArraySet;


@ServerEndpoint(value = "/log")
@Component
public class LogWebsockController {
    private Process process;
    private InputStream inputStream;
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<LogWebsockController> webSocketSet = new CopyOnWriteArraySet<LogWebsockController>();


    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        try {
            process = Runtime.getRuntime().exec("tail -f logs/imf.log");
            inputStream = process.getInputStream();
            IO_Log_Handle thread = new IO_Log_Handle(inputStream, session);
            thread.start();

        }catch (IOException e){
            e.printStackTrace();
        }

    }
    /**
     * WebSocket请求关闭
     */
    @OnClose
    public void onClose() {
        try {
            if(inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(process != null){
            process.destroy();
        }

    }

    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }

    public static synchronized void addOnlineCount() {
        LogWebsockController.onlineCount++;
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }


}