【发布时间】:2017-02-08 01:06:40
【问题描述】:
各位, 我有一个 Angular 2 Cli 项目。它是一个简单的聊天应用程序。但是由于某些原因,服务器没有向客户端接收/发送消息。没有编译错误,应用程序工作但没有套接字消息传递。 以下是每个代码的 sn-p 代码:
快递:
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
//set socket.io for chat
var io = require('socket.io').listen(server);
io.on('connnection', (socket) => {
console.log('user connected');
socket.on('message', (msg) => {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
socket.on('disconnect', () => {
console.log('user has disconnected');
});
});
server.listen(port, () => console.log("server running"));
应用组件
import { Component } 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 {
messages: Array<String>;
chatBox: String;
socket: any;
constructor() {
this.chatBox = "";
this.socket = io("http://localhost:3000");
this.socket.on("message", (msg) => {
this.messages.push(msg);
});
}
send(message) {
this.socket.emit("message", message);
this.chatBox = "";
}
}
HTML:
<ul>
<li *ngFor="let item of messages">{{item}}</li>
</ul>
<input [(ngModel)]="chatBox" autocomplete="off" />
<button (click)="send(chatBox)">Send</button>
我将不胜感激任何帮助或提示来解决这个问题。
如果我使用 html 聊天的简单基于快递的服务器可以正常工作。
谢谢
【问题讨论】:
-
是否有连接失败之类的错误?
-
没有错误,只是没有收到任何 console.log 消息
-
我说的是前端/Angular 2 ...浏览器控制台有什么错误吗?没有 console.logs,因为 socket 根本没有连接。
-
不,干净.. 完全没有错误.. 在浏览器和服务器端都没有。你的项目是基于 angular2 cli 的吗?