Angular 2 cli项目-Socket.io无法正常工作

时间:2017-02-07 12:28:54

标签: socket.io angular2-cli

民间, 我有一个有角度的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聊天工作正常。

由于

1 个答案:

答案 0 :(得分:0)

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

更改

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

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