1. 程式人生 > >Java實現websocket與微信小程式連線

Java實現websocket與微信小程式連線

微信的WebSocket介面和HTML5的WebSocket基本一樣,是HTTP協議升級來的,做為一個新的Socket在B/S上使用,它實現了瀏覽器與伺服器全雙工通訊。

 

在WebSocket出來之前,實現即時通訊通常使用Ajax來實現,而Ajax是通過輪詢的方式進行實時資料的獲取,輪詢就是在指定的時間間隔內,進行HTTP 請求來獲取資料,而這種方式會產生一些弊端,一方面產生過多的HTTP請求,佔用頻寬,增大伺服器的相應,浪費資源,另一方面,因為不是每一次請求都會有資料變化(就像聊天室),所以就會造成請求的利用率低。
 

WebSocket正好能夠解決上面的弊端,WebSocket

是客戶端與伺服器之前專門建立一條通道,請求也只請求一次,而且可以從同道中實時的獲取伺服器的資料,所以當應用到實時的應用上時,WebSocket是一個很不錯的選擇。

 

WebSocket的連結不是以httphttps開頭的,而是以wswss開頭的,這裡需要注意一下。

 

import com.ds.tech.service.SocketChatService;
import com.ds.tech.utility.log4j.LogWriter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.server.standard.SpringConfigurator;

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


//websocket連線URL地址和可被呼叫配置
@ServerEndpoint(value="/wx/{modular}/{interfaces}",configurator = SpringConfigurator.class)
public class WebSocketChatCotroller {

    private static Logger logger = Logger.getRootLogger();

    //需要session來對使用者傳送資料, 獲取連線特徵userId
    private Session session;
    private String api;


    @Autowired
    private SocketChatService service;

    /**
     * @Title: onOpen
     * @Description: websocekt連線建立時的操作
     * @param @param userId 使用者id
     * @param @param session websocket連線的session屬性
     * @param @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("modular") String modular,@PathParam("interfaces") String interfaces, Session session) throws IOException{
        this.session = session;
        this.api = "wx/"+modular+"/"+interfaces;
    }

    /**
     * @Title: onClose
     * @Description: 連線關閉的操作
     */
    @OnClose
    public void onClose(){
        logger.info(api+"連結關閉");
        this.session = null;
    }

    /**
     * @Title: onMessage
     * @Description: 收到訊息後的操作
     * @param @param message 收到的訊息
     * @param @param session 該連線的session屬性
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("介面:"+api+",入參:"+message);
        if(session ==null){
            logger.info("session null");
        }
        String apiResultString = null;
        try {
            apiResultString = service.getApi(api,message);
        }catch (Exception e){
            LogWriter.writeErrorLog("請求失敗,原因:", e);
        }
        //向客戶端傳送訊息傳送
        sendMessageToUser(this.api,apiResultString);
    }

    /**
     * @Title: onError
     * @Description: 連線發生錯誤時候的操作
     * @param @param session 該連線的session
     * @param @param error 發生的錯誤
     */
    @OnError
    public void onError(Session session, Throwable error){
        logger.info("介面:"+api+"連線時傳送錯誤:");
        error.printStackTrace();
    }

    /**
     * @Title: sendMessageToUser
     * @Description: 傳送訊息給使用者下的所有終端
     * @param @param userId 使用者id
     * @param @param message 傳送的訊息
     * @param @return 傳送成功返回true,反則返回false
     */
    public Boolean sendMessageToUser(String api,String message){
            logger.info(api+"返回引數:"+message);
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
                logger.info(api+"返回引數失敗:"+e);
                return false;
            }
            return true;
    }

}

 

import com.alibaba.fastjson.JSONObject;
import com.ds.tech.service.base.BaseService;
import com.ds.tech.utility.common.ConfigUtil;
import com.ds.tech.utility.http.HttpRequestUtil;
import com.ds.tech.utility.model.InputObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;

@Service
@Scope("prototype")
public class SocketChatService extends BaseService {
    public String getApi(String url,String message) throws IOException {
        InputObject inputObject = JSONObject.parseObject(message,InputObject.class);
        //請求引數
        String data =  inputObject.getData();
        apiParamMap.put("partner", inputObject.getPartner());
        apiParamMap.put("data", URLEncoder.encode(data, "utf-8"));
        apiParamMap.put("sign", inputObject.getSign());
        logger.info("小程式請求API系統-"+url+":"+apiParamMap);
        // 請求api
        return apiResultString = HttpRequestUtil.get(ConfigUtil.getSettings("api_host")+ url+ ".do", apiParamMap);

    }

}