12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- import IIMHandler from "../interface/i-im-handler";
- import ImApi from './../../../apis/im'
- export default class WebSocketHandlerImp extends IIMHandler {
- constructor() {
- super();
- this._socket = null
- this.im_user_id = null
- }
- register () {
- return ImApi.register({name: 'xu'}).then(res => {
- this.im_user_id = res.data.id
- return res
- })
- }
- /**
- * 创建WebSocket连接
- * 如:this.imWebSocket = new IMWebSocket();
- * this.imWebSocket.createSocket({url: 'ws://10.4.97.87:8001'});
- * 如果你使用本地服务器来测试,那么这里的url需要用ws,而不是wss,因为用wss无法成功连接到本地服务器
- * @param options 建立连接时需要的配置信息,这里是传入的url,即你的服务端地址,端口号不是必需的。
- */
- createConnection({options}) {
- this._socket = wx.connectSocket({
- url: options.url,
- header: {
- 'content-type': 'application/json'
- },
- method: 'GET'
- });
- this._onSocketOpen();
- this._onSocketMessage();
- this._onSocketError();
- this._onSocketClose();
-
- }
- _sendMsgImp({content, success, fail}) {
- this._socket.send({
- data: JSON.stringify(content),
- success: () => {
- success && success({content});
- },
- fail: (res) => {
- fail && fail(res);
- }
- });
- }
- /**
- * 关闭webSocket
- */
- closeConnection() {
- this._socket.close();
- }
- _onSocketError(cb) {
- this._socket.onError((res) => {
- this._isLogin = false;
- console.log('WebSocket连接打开失败,请检查!', res);
- })
- }
- _onSocketClose(cb) {
- this._socket.onClose((res) => {
- this._isLogin = false;
- console.log('WebSocket 已关闭!', res)
- });
- }
- _onSocketOpen() {
- ImApi.getContacts(getApp().globalData.userinfo.user_id)
- this._socket.onOpen((res) => {
- console.log('WebSocket连接已打开!');
- });
- }
- /**
- * webSocket是在这里接收消息的
- * 在socket连接成功时,服务器会主动给客户端推送一条消息类型为login的信息,携带了用户的基本信息,如id,头像和昵称。
- * 在login信息接收前发送的所有消息,都会被推到msgQueue队列中,在登录成功后会自动重新发送。
- * 这里我进行了事件的分发,接收到非login类型的消息,会回调监听函数。
- * @private
- */
- _onSocketMessage() {
- this._socket.onMessage((res) => {
- let msg = JSON.parse(res.data);
- if (msg.type === 'TYPE_ONE') {
- this._receiveListener && this._receiveListener(msg);
- }
- })
- }
- }
|