客户端我使用 Angular 6,服务器端我使用 node.js。
在 Angular 6 控制台中,它打印消息并
socket.io id({message: "Hello World", id: "6An-ctwlwbZZWrfMAAAB"})
使用下面的代码后。
此代码是正确的,或者此代码有任何更改,因为我不确定此代码,请帮助纠正此问题。
另一个问题是我的项目中有超过 15 个组件,因此如何为所有组件共同使用这个 socket.io
或者我必须导入这个 app.component.ts
所有其他组件中的代码。
app.js(服务器端)
after installing (npm i socket.io)
const express = require('express');
var app = express();
const http = require('http');
const socketIo = require('socket.io');
const server = http.Server(app);
const io = socketIo(server);
server.listen(3000,function(req,res){
console.log("listen at 3000!");
});
io.on('connection',(socket) => {
socket.emit('hello',{
message : 'Hello World',id: socket.id
})
});
app.component.ts(客户端)
after installing (npm i socket.io)
import * as socketIo from 'socket.io-client';
export class AppComponent implements OnInit {
ngOnInit(){
const socket = socketIo('http://localhost:3000/');
socket.on('hello',(data) => console.log(data));
}
}
}
最佳答案
实现此机制的一种方法是使用 ngx-socket-io
,在模块级别或根级别连接 Node 服务器,如下所示
app.module.ts代码
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { AppComponent } from './app.component';
const config: SocketIoConfig = { url: 'http://192.168.1.187:9301', options: {} };
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
SocketIoModule.forRoot(config),
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
创建一项服务来处理传入和传出流量。
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Injectable({
providedIn: 'root'
})
export class SocketService {
constructor(public socket: Socket) { }
getMessage() {
return this.socket
.fromEvent<any>('msg')
.map(data => data.msg);
}
sendMessage(msg: string) {
this.socket.emit('msg', msg);
}
}
更新组件文件中的代码
export class AppComponent implements OnInit {
constructor(private socketService: SocketService) {}
title = 'app';
incomingmsg = [];
msg = 'First Protocol';
ngOnInit() {
this.socketService
.getMessage()
.subscribe(msg => {
console.log('Incoming msg', msg);
});
this.sendMsg(this.msg);
}
sendMsg(msg) {
console.log('sdsd', msg);
this.socketService.sendMessage(msg);
}
}
关于node.js - 如何在 Angular 和 Node.js 中使用 socket.io?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566563/