【发布时间】: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