Angular 6和Socket.IO-Socket.On无法正常工作

时间:2018-08-23 00:18:51

标签: angular socket.io mean-stack angular6

我正在尝试将Socket.io与Angular 6项目一起使用,但似乎无法正常工作。这是我的问题:

我已经安装了socket.io-client(使用npm)

这是我的服务器代码:

var express = require('express');

var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json());

var path = require('path');

app.use(express.static(__dirname + '/client/public/dist/public'));

var db_url = 'mongodb://localhost:27017/DBName'

require('./server/config/mongoose.js')(db_url);

require('./server/config/routes.js')(app)

app.all("*", (req,res,next) => {
    res.sendFile(path.resolve("./client/public/dist/public/index.html"))
  });

const server = app.listen(1337);
console.log("listening on port 1337")

const io = require('socket.io')(server);

io.on('connection', function (socket) {

    socket.on('init',function(){      
        console.log("Socket id is",socket.id)
        io.emit('message',{msg:'testing socket'})
        console.log("after emit statement")
    })

});

app.listen(8000, function() {
    console.log("listening on port 8000");
})

在我的Angular项目中,我位于组件的ts文件(my-rooms.component.ts)中,代码如下:

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../http.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';

@Component({
  selector: 'app-my-rooms',
  templateUrl: './my-rooms.component.html',
  styleUrls: ['./my-rooms.component.css']
})

export class MyRoomsComponent implements OnInit {
  user_email = localStorage.getItem('email');
  new_room = {name:""};
  errors = {};
  all_rooms = [];
  joined_rooms = [];
  socket: SocketIOClient.Socket;

  constructor(private _httpService: HttpService,
    private _route: ActivatedRoute,
    private _router: Router) {
      this.socket = io.connect();
     }

  ngOnInit() {
    console.log(localStorage)
    if (!localStorage.getItem('loggedIn')) {
      this._router.navigate(['/home']);
    }
    else {
      this.getAllRooms();
      this.getJoinedRooms();
    }

    this.socket.emit('init');
    this.socket.on('message',function(data){
      console.log(data.msg)
    }) 
  }

//Plus other functions for this component

基本上,没有任何记录在终端或浏览器的控制台中。有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您应该收听Node Js Port

<!DOCTYPE html>
<html>

<body>
  <style>
    .myClass {
      color: black;
      background-color: white;
      text-align: left;
      margin: auto;
      font-size: auto;
      width: auto;
    }
  </style>
  <template>
		<div class="myClass"></div>
	</template>
  <title>Sprinkler System</title>
  <p id="System" class="myClass"></p>
  <p id="PumpPres" class="myClass"></p>
  <p id="PumpCurrent" class="myClass"></p>
  <h6><i>This is in develoupement build</i></h6>

  <h3>Message<br>
    <input type="text" id="InputRandom"></input> <input onclick="Random1()" type="button" value="Send Message" id="Input2"></input>
  </h3>
  <br>
  <h4> Sprinkler System <br><input type="number" id="InputTxt" min="1" max="12"></input>
    <input onclick="SS_On()" type="button" value="Turn On"></input>
    <input onclick="SS_Off()" type="button" value="Turn Off" id="RandomBtn"></input>
  </h4>
  <p id="this" class="myClass"></p>
  <input onclick="reset()" type="button" value="reset"></input>
  <p id="mic"></p>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>

  <script>
    /*=============================================Variables================================================*/
    var HomeLog = "home/irrigation/state";
    var LogSS = "home/irrigation/log";
    var SS_dest = "home/irrigation"; //SS == Sprinkler System
    var SS_Pres = "home/irrigation/pressure";
    var SS_Current = "home/irrigation/pump_current"
    var Ip = "192.168.1.46"; //ip adress of the broker
    var Port = Number(8083); //port of the broker
    var Id = makeid(); //writes the ip
    var mes; //makes mes global
    var num = 0;
    var Log;
    /*==============================================MQTT====================================*/
    client = new Paho.MQTT.Client(Ip, Port, Id);

    // set callback handlers
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;

    // connect the client
    client.connect({
      onSuccess: onConnect
    });

    // called when the client connects
    function onConnect() {

      // Once a connection has been made, make a subscription and send a message.
      console.log("Connected as " + makeid());
      client.subscribe(SS_dest);
      client.subscribe(LogSS);
      client.subscribe(HomeLog);
      client.subscribe(SS_Pres);
      client.subscribe(SS_Current);
    }

    // called when the client loses its connection
    function onConnectionLost(responseObject) {
      var TimeOut;
      var Object1 = responseObject.errorCode;
      if (Object1 !== 0) {
        console.log("ConnectionLost:" + responseObject.errorMessage);
        //client = new Paho.MQTT.Client(Ip, Port, Id);
        client.connect({
          onSuccess: onConnect
        });
        TimeOut++;
      }
      if (TimeOut == 10) {
        Object1 = 1;
      }
    }

    // called when a message arrives
    function onMessageArrived(message) {
      var OnOff;
      console.log("MessageArrived:" + message.payloadString);
      mes = message.payloadString;
      //alert(mes);


      var res = mes.split(","); //holds if statement
      if (res[1] == "on" || res[1] == "On") {
        OnOff = "On";

      } else if (res[1] == "Off" || res[1] == "Off") {
        OnOff = "Off";
      }
      var Test1 = res.length;
      if (Test1 >= 2) {
        //alert(Test1);
        document.getElementById("p" + res[0]).innerHTML = "Zone " + res[0] + " == " + OnOff;
      }
      console.log("Topic:     " + message.destinationName);
      Log = message.destinationName;
      console.log(Log);
      if (Log == "home/irrigation/state") {
        document.getElementById("System").innerHTML = "Pump == " + mes;
      }
      if (Log == "home/irrigation/pressure") {
        document.getElementById('PumpPres').innerHTML = "Presure == " + mes;
      }
      if (Log == "home/irrigation/pump_current") {
        document.getElementById('PumpCurrent').innerHTML = "Current == " + mes;
      }
      if (Log != "home/irrigation/pump_current" && Log != "home/irrigation/pressure") {
        document.getElementById("mic").innerHTML = document.getElementById("mic").textContent + "," + mes;
        document.getElementById("mic").style.fontSize = "small";
        num = num + 1;
        Loop1();
      }
    }
    /*==========================================Functions=================================*/
    makeBigger();
    test();

    function SS_On() { //turn on the system
      var elem = document.getElementById("InputTxt") //gets the input of the textbox
      if (elem.value < 13 && elem.value >= 1) { //detects if the input is in a certan range
        message = new Paho.MQTT.Message(elem.value + ",On"); //wrights a message
        message.destinationName = SS_dest; //sets the destonation of the message
        client.send(message); //sends the message to the broker
      }
    }

    function SS_Off() { //turn off the system
      var elem = document.getElementById("InputTxt") //gets the input of the textbox
      if (elem.value < 13 && elem.value >= 1) { //detects if the input is in a certan range
        message = new Paho.MQTT.Message(elem.value + ",Off"); //wrights a message
        message.destinationName = SS_dest; //sets the destonation of the message
        client.send(message); //sends the message to the broker
      }
    }

    function makeid() { //this is made to make a randomized id
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.";

      for (var i = 0; i < 5; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

      return text;

    }

    function Random1() { //made for a helloworld
      var elem1 = document.getElementById("InputRandom");
      message = new Paho.MQTT.Message(elem1.value); //wrights a message
      message.destinationName = LogSS; //sets the destonation of the message
      client.send(message); //sends the message to the broker
    }

    function Loop1() { //made to reset the log
      if (num == 5) {
        document.getElementById("mic").innerHTML = mes;
        num = 0;

      }
    }

    function reset() { //ment for the reset button
      num = 0;
      document.getElementById("mic").innerHTML = " ";

    }

    function test() { //this is made to make the p1-p12 in the HTML
      for (nom = 1; nom <= 12; nom++) {
        document.getElementById("this").innerHTML = document.getElementById("this").innerHTML + "<p id=p" + nom + " class=myClass>Zone " + nom + " == Off</p>";
      }
    }

    function makeBigger() {
      var txt = document.getElementById("InputTxt");
      txt.style['width'] = '165px';
    }
  </script>
</body>

</html>