【问题标题】:SocketIO events are not triggered when webapp is opened in mobile device在移动设备中打开 webapp 时不会触发 SocketIO 事件
【发布时间】:2020-12-25 16:43:48
【问题描述】:

我正在开发一个简单的应用程序,一旦用户成功登录,就会触发事件。

所有事件在我的笔记本电脑上都可以正常工作,但是当我从手机登录时,没有触发任何事件?有什么可能的原因吗?

在下面添加了 Angular 套接字服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class SocketService {
  public prod = 'https://afad.sdfsd.com';
  public dev = 'http://localhost:3001';
  public baseUrl = this.dev;
  private socket;
  constructor(public http: HttpClient) {
    this.socket=io('https://dfdsfs.sdfs.com')
   }
   public verifyUser=()=>{
     return Observable.create((observer)=>{
       this.socket.on('verifyUser',(data)=>{
         observer.next(data);
       })
     })
   }
   public setUser=(authToken)=>{
     this.socket.emit("set-user",authToken)
   }
   public userOffline=()=>{
    return Observable.create((observer)=>{
      this.socket.on('userOffline',(data)=>{
        observer.next(data);
      })
    })
  }
 
   public userList=()=>{
    return Observable.create((observer)=>{
      this.socket.on('userlist',(data)=>{
        observer.next(data);
      })
    })
  }
  public welcomeUser=(userid)=>{
    return Observable.create((observer)=>{
      this.socket.on(userid,(data)=>{
        observer.next(data);
      })
    })
  }
  public userOnline=()=>{
    return Observable.create((observer)=>{
      this.socket.on('userOnline',(data)=>{
        observer.next(data);
      })
    })
  }
  public disconnectUser = () => {
    return Observable.create((observer) => {
      this.socket.on('disconnect', () => {
        observer.next()
      })
    })
  }    
}

我已经安装了socketio-client 来实现这个功能。

任何突破都会有帮助

【问题讨论】:

    标签: node.js angular websocket socket.io


    【解决方案1】:

    我能够在这里找出问题所在, socket.emit 将向当前用户发出一个事件,在这种情况下我们应该使用 myio.emit。

    【讨论】:

      【解决方案2】:

      我猜你的笔记本电脑和手机是通过 WIFI 连接到路由器的。如果是这样,您将无法使用 https://afad.sdfsd.com 或 http://localhost:3001,因为它们只能在笔记本电脑上使用。

      尝试从浏览器中提取主机名并将其用作基本 URL (window.location.host)

      当您使用笔记本电脑时,它将是 localhost:3001,而对于手机,它将是 IP_OF_THE_3001。

      ...
      export class SocketService {
      
        private socket;
        constructor(public http: HttpClient) {
          this.socket=io(window.location.host)
         }
      ...
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-16
        • 2015-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多