伙计们,我有一个 Angular 2 Cli 项目。它是一个简单的聊天应用程序。但是由于某些原因,服务器没有向客户端接收/发送消息。没有编译错误,应用程序工作但没有套接字消息传递。以下是每个的代码片段:
表达:
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 聊天的简单基于快递的服务器工作正常。
谢谢