node.js - Socket Io bulunamadı 404


Bu eğitime dayalı olarak Angular 2'de Socket IO kullanarak bir sohbet oluşturmaya çalışıyorum, ancak sunucuda bir test yapmaya çalıştığımda bu hata mesajını alıyorum:

GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LmD1N_Z 404 (Bulunamadı)

Uygulama port 3000 üzerinde çalışırken sunucu port 8000 üzerinde çalışıyor ve sanırım bu yüzden bu hatayı alıyorum. Hem sunucu hem de uygulamanın aynı portta çalışmasının bir yolu var mı?

İşte uygulamadan bazı kodlar: Bu, testi yapmaya çalıştığım bileşen:

import { Component, OnInit} from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Location} from '@angular/common';
import {Routes, RouterModule, Router} from '@angular/router';
import * as io from 'socket.io-client'

@Component({
  moduleId: module.id,
  selector: 'atendimento',
  templateUrl: `atendimento.component.html`
})

export class AtendimentoComponent implements OnInit{
  socket:SocketIOClient.Socket;
  constructor(private location: Location) { 
    this.socket = io.connect();
  }

  ngOnInit(){
    this.socket.emit('event1',{
      msg: 'Can you hear me? Over'
    });
    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)
    })
  }

Ve bu, sunucu ile bağlantıyı kurduğum server.js dosyası:

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

const port = 8000;

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

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

Biri bana yardım edebilir mi? Teşekkürler, daha fazla koda ihtiyacın olursa haber ver.

Cevap #1

Doğru sunucu URL'si ile socket io'yu bağlayın:

değiştir :

this.socket = io.connect();

ile :

this.socket = io('http://localhost:8000');