【问题标题】:Socket Io not found 404未找到套接字 Io 404
【发布时间】:2017-10-14 13:41:19
【问题描述】:

我正在尝试使用基于 tutorial 的 Socket IO 在 Angular 2 中创建聊天,但是当我尝试在服务器上进行测试时收到此错误消息:

获取 http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LmD1N_Z404 (未找到)

应用程序在port 3000 上运行,而服务器在port 8000 上运行,我认为这就是我收到此错误的原因。有没有办法让服务器和应用程序都在同一个端口上运行?

以下是应用程序中的一些代码: 这是我正在尝试进行测试的组件:

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

这是我与服务器建立连接的server.js

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

有人可以帮助我吗?谢谢,如果您需要更多代码,请告诉我。

【问题讨论】:

    标签: node.js angular typescript socket.io


    【解决方案1】:

    只需将套接字 io 与正确的服务器 url 连接:

    替换:

    this.socket = io.connect();
    

    与:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 2022-01-22
      • 2019-02-20
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多