Websocket实时推送日志到前端
作者:互联网
1、使用RandomAccessFile读文件
2、每次开始读时,先进行一次全读,目的是让seek到结尾。
3、注意编码转换。RandomAccessFile的编码都是ISO_8859_1
@OnOpen
public void onOpen(Session session) {
onlineCount.incrementAndGet(); // 在线数加1
log.info("有新连接加入:{},当前在线人数为:{}", session.getId(), onlineCount.get());
try {
RandomAccessFile r = new RandomAccessFile("case.log", "r");
byte[] bf = new byte[1024*100];
while (r.read(bf) != -1) {}
long lastPonit = r.getFilePointer();
String line = null;
while (true) {
r.seek(lastPonit);
while ((line = r.readLine()) != null) {
session.getBasicRemote().sendText(new String(line.getBytes(StandardCharsets.ISO_8859_1), "UTF-8") + "\n");
}
lastPonit = r.getFilePointer();
}
} catch (Exception e) {}
}
标签:Websocket,lastPonit,RandomAccessFile,while,session,new,日志,推送,line 来源: https://www.cnblogs.com/coder-huang89/p/15879891.html