html5 websocket 实时日志推送

package com.zt1953.logserver;

import org.glassfish.tyrus.server.Server;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by sunyl on 15/5/27.
 */
public class WebSocketServer {
    public static void main(String[] args) {
        runServer();
    }

    public static void runServer() {
        Server server = new Server("localhost", 8888, "/logserver", LogServerEndpoint.class);

        try {
            server.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Please press a key to stop the server.");
            reader.readLine();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            server.stop();
        }
    }
}

package com.zt1953.logserver;

import javax.websocket.Session;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by sunyl on 15/5/27.
 */
public class MessageSender {
    private volatile static Map sessionMap = new HashMap();


    static final Logger logger = Logger.getLogger(MessageSender.class.getName());

    public void addSession(String key, Session session) {
        sessionMap.put(key, session);
        MsgThread thread = new MsgThread(session);
        thread.start();

    }


    public void removeSession(String key) {
        sessionMap.remove(key);
    }


}

class MsgThread extends Thread {
    private File logfile = new File("/usr/local/java/zt1953-logs/logs.log");
    private Session session;

    File file = null;
    RandomAccessFile randomFile = null;

    public MsgThread(Session session) {
        this.session = session;

        file = new File("/usr/local/java/zt1953-logs/logs.log");
        try {
            randomFile = new RandomAccessFile(file, "rw");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            long filePointer = this.logfile.length();
            RandomAccessFile file = new RandomAccessFile(logfile, "r");
            while (true) {
                long fileLength = this.logfile.length();
                if (fileLength < filePointer) {
                    file = new RandomAccessFile(logfile, "r");
                    filePointer = 0;
                }
                if (fileLength > filePointer) {
                    file.seek(filePointer);
                    String line = new String(file.readLine().getBytes("iso8859-1"), "utf-8");
                    while (line != null) {
                        this.session.getAsyncRemote().sendText(line);
                        line = null;
                        filePointer = file.getFilePointer();
                    }

                }
                sleep(500);
            }

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

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

        }
    }


}

package com.zt1953.logserver;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by sunyl on 15/5/27.
 */
@ServerEndpoint(value = "/logs")
public class LogServerEndpoint {
    static volatile List sessionList = new ArrayList();

    private Logger logger = Logger.getLogger(this.getClass().getName());

    MessageSender messageSender = new MessageSender();

    @OnOpen
    public void onOpen(Session session) {

        try {
            logger.info("add session");
            sessionList.add(session);
            logger.info("Connected ... " + session.getId());

            messageSender.addSession(session.getId(), session);
            logger.info("current session list:" + sessionList.size());

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

    @OnMessage
    public String onMessage(String message, Session session) {
        logger.info("on message:" + message);
        switch (message) {
            case "quit":
                try {
                    session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Game ended"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                break;
        }
        return message;
    }


    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        logger.info(String.format("Session %s closed because of %s", session.getId(), closeReason));
    }
}








    Testing websockets



html5 websocket 实时日志推送_第1张图片



    4.0.0

    com.zt1953
    zt1953-websocket-log
    1.0-SNAPSHOT

    
        
            javax.websocket
            javax.websocket-api
            1.0
        
        
            org.glassfish.tyrus
            tyrus-server
            1.1
        
        
            org.glassfish.tyrus
            tyrus-client
            1.1
        
        
            org.glassfish.tyrus
            tyrus-container-grizzly
            1.1
        

    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    1.7
                    1.7
                    1.7
                
            
        
    

实时读入文件内容发送给客户端

你可能感兴趣的:(html5 websocket 实时日志推送)