简体   繁体   English

如何在 angular 4 中使用 socket.io-client

[英]How to use socket.io-client in angular 4

Server side is php laravel echo websocket and I am trying to connect by Angular 4. I tried using ng2-socket-io - npm and also laravel-echo - npm but none of them were successfully.服务器端是 php laravel echo websocket,我正在尝试通过 Angular 4 进行连接。我尝试使用 ng2-socket-io - npm 和 laravel-echo - npm,但没有一个成功。 If anyone know any documentation or tutorial how I can use it, please help如果有人知道我如何使用它的任何文档或教程,请帮助

Hi @giga Working example is given below.嗨@giga 下面给出了工作示例。

SETUP设置

npm i socket.io-client --save
npm i @types/socket.io-client --save

Server-side (nodejs)服务器端(nodejs)

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var port = 8000;

app.use(express.static(path.join(__dirname, "public")));

io.on('connection', (socket) => {
console.log('new connection made');

socket.on('event1', (data) => {
  console.log(data.msg);
});

socket.emit('event2', {
  msg: 'Server to client, do you read me? Over.'
});

socket.on('event3', (data) => {
  console.log(data.msg);
  socket.emit('event4', {
    msg: 'Loud and clear :)'
  });
});
});

server.listen(port, () => {
  console.log("Listening on port " + port);
});

Client-side - Angular4 code客户端 - Angular4 代码

import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';

@Component({
    moduleId: module.id,
    selector: 'ch-home',
    styleUrls: ['home.styles.css'],
    templateUrl: 'home.template.html'
})

export class HomeComponent implements OnInit {
    messageText: string;
    messages: Array<any>;
    socket: SocketIOClient.Socket;

  constructor() {
   // this.socket = io.connect('http://localhost:8000');
   this.socket = io.connect();
  }

  ngOnInit() {
        this.messages = new Array();

        this.socket.on('message-received', (msg: any) => {
            this.messages.push(msg);
            console.log(msg);
            console.log(this.messages);
        });
      this.socket.emit('event1', {
          msg: 'Client to server, can you hear me server?'
      });
      this.socket.on('event2', (data: any) => {
        console.log(data.msg);
        this.socket.emit('event3', {
            msg: 'Yes, its working for me!!'
        });
      });
      this.socket.on('event4', (data: any) => {
          console.log(data.msg);
      });
   }

   sendMessage() {
    const message = {
      text: this.messageText
    };
    this.socket.emit('send-message', message);
    // console.log(message.text);
    this.messageText = '';
  }

}

Implement socket.io-client as an Angular service将 socket.io-client 实现为 Angular 服务

Setup设置

npm install socket.io-client --save

Note 2021: Do not install @types/socket.io-client since the types are now included in the socket.io-client (v3) package and thus may cause issues ( source ).注意 2021:不要安装@types/socket.io-client因为这些类型现在包含在socket.io-client (v3) 包中,因此可能会导致问题( source )。

The service:服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { io, Socket } from 'socket.io-client';

@Injectable()
export class ChatService {
  private socket: Socket;

  constructor() {
    this.socket = io('http://localhost:3000');
  }

  // EMITTER example
  sendMessage(msg: string) {
    this.socket.emit('sendMessage', { message: msg });
  }

  // HANDLER example
  onNewMessage() {
    return new Observable(observer => {
      this.socket.on('newMessage', msg => {
        observer.next(msg);
      });
    });
  }
}

In a component:在一个组件中:

import { Component, OnInit } from '@angular/core';
import { ChatService } from './chat-service';

@Component({
  // ...blabla...
})
export class ChatComponent implements OnInit {
  msgInput: string = 'lorem ipsum';

  constructor(
    private chatService: ChatService,
  ) { }

  ngOnInit() {
    this.chatService.onNewMessage().subscribe(msg => {
      console.log('got a msg: ' + msg);
    });
  }

  sendButtonClick() {
    this.chatService.sendMessage(this.msgInput);
  }
}

Following the solution of @MA-Maddin, I did this implementation:按照@MA-Maddin的解决方案,我做了这个实现:

at Service :socket.service在服务:socket.service

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SocketService {
private socket:SocketIOClient.Socket;

constructor() { 
  this.socket=io('http://localhost:3300');
}
emit(event:string, data:any){
  this.socket.emit(event,data);
}
on(event:string){
  return Observable.create(observer=>{
   this.socket.on(event,data=>{
    observer.next(data);
   });
  })
 }
}

At Component在组件

 import { Component, OnInit, Input, ViewChild, ViewEncapsulation} from 
'@angular/core';
import { AuthService } from 'src/app/auth/auth.service';
import Socket from '../../services/socket.service';

@Component({
  selector: 'app-lobby-chat',
  templateUrl: './lobby-chat.component.html',
  styleUrls: ['./lobby-chat.component.css'],
  encapsulation: ViewEncapsulation.None,
})
export class LobbyChatComponent implements OnInit {
  constructor(private socket:Socket) {
  this.socket.on('getMessage').subscribe(data=>{
  console.log(data);
  });
  }
  pushMessage(msg){
  this.socket.emit('sendMessage',msg);
  }
}

This will update your bindings correctly.这将正确更新您的绑定。 Note: **use npm i "@types/socket.io-client for use or define Socket io Types **注意:**使用 npm i "@types/socket.io-client 来使用或定义 Socket io 类型 **

此外,您需要安装 VithuBati 的答案: npm i socket.io-client --save npm i @types/socket.io-client --save

I know its an old question , For me none of the solutions worked so I solved with below approach.我知道这是一个老问题,对我来说,没有一个解决方案有效,所以我用下面的方法解决了。

Do Not Waste your time if your socket connection polling is working fine and not getting any error , It might be due to the socket.io.client package conflict with your other setup如果您的套接字连接轮询工作正常并且没有出现任何错误,请不要浪费您的时间,这可能是由于 socket.io.client 包与您的其他设置冲突

my application version are below.我的应用程序版本如下。

Angular 12.x Socket.io.client 4.x Node 14.16.1 I also tried with ngx-socket-io package too that also didn't work. Angular 12.x Socket.io.client 4.x Node 14.16.1我也尝试过 ngx-socket-io 包,但也没有用。 the strange part is socket.io poling works well hand shaking are correct but not able to listen the event on new messages.奇怪的部分是 socket.io poling 效果很好,握手是正确的,但无法监听新消息的事件。

So my final approach is adding socket.io manully to index.html of angular and dispatch and event to the compoent.所以我最后的方法是将 socket.io 手动添加到 index.html 的 angular 和 dispatch 和 event 到组件。

function RsCustomEvent ( event, message ) {
    params = { bubbles: false, cancelable: false, detail: message };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
}
var socket = io('localhost:3000');
socket.on("channel-name", function (message) {
    window.dispatchEvent(RsCustomEvent('socketEventListen',message));

});

then in the angular component I used below codes.然后在我在下面的代码中使用的角度组件中。

 import { Observable , fromEvent} from 'rxjs';


fromEvent(window, 'socketEventListen').subscribe((data) =>{
 });

manually download the socket.io client js file and place that in asset folder and use the above codes.手动下载 socket.io 客户端 js 文件并将其放在资产文件夹中并使用上述代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM