Java实现websocket与微信小程序链接

微信的WebSocket接口和HTML5的WebSocket基本同样,是HTTP协议升级来的,作为一个新的Socket在B/S上使用,它实现了浏览器与服务器全双工通讯。java

 

在WebSocket出来以前,实现即时通信一般使用Ajax来实现,而Ajax是经过轮询的方式进行实时数据的获取,轮询就是在指定的时间间隔内,进行HTTP 请求来获取数据,而这种方式会产生一些弊端,一方面产生过多的HTTP请求,占用带宽,增大服务器的相应,浪费资源,另外一方面,由于不是每一次请求都会有数据变化(就像聊天室),因此就会形成请求的利用率低。
 web

WebSocket正好可以解决上面的弊端,WebSocket是客户端与服务器以前专门创建一条通道,请求也只请求一次,并且能够从同道中实时的获取服务器的数据,因此当应用到实时的应用上时,WebSocket是一个很不错的选择。spring

 

WebSocket的连接不是以httphttps开头的,而是以wswss开头的,这里须要注意一下。apache

 

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;json

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 {api

    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);

    }

}  

相关文章
相关标签/搜索