【问题标题】:Angular 2 cli project -Socket.io not workingAngular 2 cli 项目-Socket.io 不工作
【发布时间】: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 的吗?

标签: socket.io angular2-cli


【解决方案1】:

根本没有连接到套接字的代码。

改变

this.socket = io("http://localhost:3000");

   this.socket=io.connect("http://localhost:3000")

【讨论】:

  • 没有帮助....您是如何在客户端阅读 socket.io 的?您是否在 angular-cli.json 上添加脚本或将 放入 index.html 或放入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多