【问题标题】:Socket -io client is not connecting to node-js socket ioSocket -io 客户端未连接到 node-js 套接字 io
【发布时间】:2021-09-14 10:11:14
【问题描述】:

我正在尝试在离子电容器(基于角度的应用程序)中实现 socket-io-client,但无法将客户端连接到服务器。

这是我正在使用应用内模块的套接字服务。

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import {environment} from '../environments/environment'

  @Injectable({
  providedIn: 'root'
   

    import { Injectable } from '@angular/core';
    import * as io from 'socket.io-client';
    import {environment} from '../environments/environment'

    @Injectable({
      providedIn: 'root'
    })
    export class SocketioService {
      socket:any;
      constructor() { 
        this.socket = io('http://localhost:5000',{ transports : ['websocket'] });
        console.log("socket",this.socket)
      }
      setupSocketConnection() {
        console.log("socketio from socket service")
        this.socket = io(environment.SOCKET_ENDPOINT);
        console.log("socket",this.socket)
        this.socket.emit('my message', 'Hello there from Angular.');
        this.socket.on("test",(arg)=>{
          console.log(arg)
        })
      }
    }
<!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js -->

这是我尝试在客户端控制套接字时得到的结果

socket from app 
     p
     acks: {0: ƒ}
     connected: false
     disconnected: true
     flags: {}
     ids: 1
     io: p {nsps: {…}, subs: Array(3), opts: {…}, _reconnection: true, _reconnectionAttempts: Infinity, …}
     json: p {io: p, nsp: "/", json: p, ids: 1, acks: {…}, …}
     nsp: "/"
     receiveBuffer: []
     sendBuffer: [{…}]
     subs: (3) [{…}, {…}, {…}]
     _callbacks: {$connecting: Array(1), $connect: Array(1), $connection: Array(1)}
     __proto__: Object

【问题讨论】:

    标签: node.js angular sockets ionic-framework ionic4


    【解决方案1】:

    您应该为客户端使用ngx-socket-io Library,而不是使用socket.io-client 库。

    在你的app.module.ts里面

    像这样导入:

    import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
    const config: SocketIoConfig = { url: 'http://localhost:8081', options: {} };
    
    @NgModule({
      ...
      imports: [
          ...
        SocketIoModule.forRoot(config),
        ...
      ],
      ..
    })
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多