Jay
Jay

Reputation: 87

Use of socket io, nodejs + angular

I am very new to socket Io, node and angular. I am currently working on namespace but I can't really connect to the other namespace. Could you please have a look at what am I doing wrong?

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');
  }

if a user access to http://localhost:3000/nsp then console should prints nsp connected that i have declared in nsp.on('connection',(socket) =>{console.log('nsp connected');

Upvotes: 1

Views: 168

Answers (1)

Shanil Arjuna
Shanil Arjuna

Reputation: 1135

Since your route is as /api/nsp and not just /nsp your code in App.component.ts should be as follow :

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

Upvotes: 1

Related Questions