1. 程式人生 > >spring-boot框架下的websocket服務

spring-boot框架下的websocket服務

spring-boot websocket

這幾天在做web端實時展示服務端日誌文件新增內容的功能。要滿足實時的需求,我選擇的方案是在web端跟服務端建立一個websocket鏈接,由服務端通過tail -f 命令將文件新增內容發送給web端。

關於websocket的介紹,可以參考這篇博文:http://www.cnblogs.com/lizhenghn/p/5155933.html(鏈接僅用於學習交流,如有版權問題請及時告知)。這裏我主要想介紹的是在spring-boot框架下如何發布websocket服務。

一、在服務端發布websocket服務

服務端發布websocket服務有幾種方式,包括Servlet容器掃描初始化、Spring掃描初始化。我使用的是第二種方式,可以將websocket服務定義為一個單獨的類實例。

Spring掃描初始化時,需要先定義一個Bean:ServerEndpointExporter,以聲明服務端。我把這個Bean獨立放到一個websocket 配置類中。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
	@Bean  
    public ServerEndpointExporter serverEndpointExporter (){  
        return new ServerEndpointExporter();  
    }  

}

接下來是定義websocket服務接口,並使用關鍵字 @ServerEndpoint("/websocketPath") 聲明一個接口的訪問路徑。

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

@ServerEndpoint("/logWebsocket")  
@Component 
@RestController
public class LogWebSocketHandle {
	
    private Session session;//每個websocket會話連接對應一個session
    private static CopyOnWriteArraySet<LogWebSocketHandle> webSocketSet = new CopyOnWriteArraySet<>(); 
    
    /**
     * 新的WebSocket請求開啟。
     * 新建立連接後會觸發onOpen方法
     * @throws JSchException 
     * @throws IOException 
     */
    @OnOpen
    public void onOpen(Session session) throws JSchException, IOException {
    	this.session = session;
    	webSocketSet.add(this);
    	//服務端保留session信息,並返回結果給客戶端
    	//這個語句用於服務端給客戶端發送數據
    	session.getBasicRemote().sendText("正在獲取日誌<br>");    	   	
    }

    /**
     * WebSocket請求關閉。
     * websocket連接關閉後,會觸發onClose方法
     */
    @OnClose
    public void onClose() {
    	webSocketSet.remove(this);                
    }

    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }
    
    /**
    * 客戶端發送消息時,服務端通過onMessage方法接收
    */
    @OnMessage
    public void onMessage (String message, Session session) throws IOException, JSchException, InterruptedException {  
        LOG.info("來自客戶端的message:" + message);            	
        try {        	
    		//process message
    		//TODO
        } catch (IOException e) {
            e.printStackTrace();
        }
// 給客戶端群發消息  
//        for ( Session item : webSocketSet ){  
//                item.getBasicRemote().sendText(message);  
//        }  
    }         
}

二、web端建立websocket連接

var websocket_host = window.location.host;
//與服務端建立websocket連接
var websocket = new WebSocket("ws://"+websocket_host+"/項目名/logWebsocket");
//連接建立後,會觸發onopen方法
websocket.onopen = function(event){
	console.log("opened!");
	$("#chart_multiple div").append(event.data);
	//向服務端發送數據
	websocket.send(message);
};
//接收服務端的數據
websocket.onmessage = function(event){
	$("#chart_multiple div").append(event.data);
	$("#chart_multiple").scrollTop(
	    $("#chart_multiple div").height()-$("#chart_multiple").height()
	);
}



本文出自 “走在IT路上” 博客,請務必保留此出處http://andrewli.blog.51cto.com/7625043/1965589

spring-boot框架下的websocket服務