我对套接字Io,节点和角度非常陌生。我目前正在使用名称空间,但是我无法真正连接到其他名称空间。你能看看我在做什么错吗?
Server.js
const express = require('express')
const app = express();
const path = require('path');
const http = require('http').Server(app);
const io = require('socket.io')(http);
//namespace
var nsp = io.of('/nsp');
//when nsp connected
nsp.on('connection', (socket) =>{
console.log('nsp connected');
//when nsp disconnected
nsp.on('disconnect', function(){
console.log('nsp disconnected');
});
});
//route for nsp
app.get('/nsp', (req, res) => {
res.send(console.log('Hello'));
});
App.component.ts
import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
nsp;
constructor() {
this.nsp = io('http://localhost:3000/nsp');
}
如果用户访问
http://localhost:3000/nsp,然后控制台应打印我在nsp.on('connection',(socket) =>{console.log('nsp connected');
中声明的已连接nsp
答案 0 :(得分:0)
由于您的路由为 / api / nsp 而不是 / nsp ,因此您在 App.component.ts 中的代码应如下:
constructor() {
this.nsp = io('http://localhost:3000/api/nsp');
}