Socket.IO/向特定套接字ID的角度发射不起作用

时间:2018-08-25 01:04:48

标签: angular socket.io angular6

使用套接字和Angular,并且在向特定的socket.id发送信息时遇到问题。

在服务器中,我跟踪这样连接到网站的用户:

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);

//Tracking connected users

let connected_users = [];

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

    socket.on('init',function(data){

        var objIndex = connected_users.findIndex(function (obj) { return obj.user === data['user_email']; });

        if (objIndex == -1) {
            new_connected_user = {'user':data['user_email'],'socket_id':socket.id}
            connected_users.push(new_connected_user)
            console.log("user not found. connected users currently is ",connected_users)
        }
        else {
            connected_users[objIndex].socket_id = socket.id
            console.log("user found. connected users currently is ",connected_users)
        }
    })

    socket.on('addedFriend',function(data){
        var obj = connected_users.findIndex(function (obj) { return obj.user === data['addedFriend']['email']; });
        receiver = connected_users[obj];
        io.to(`${receiver['socket_id']}`).emit('youwereadded','You have been added to a room');    
    })

});

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

主要问题在于此代码:

socket.on('addedFriend',function(data){
            var obj = connected_users.findIndex(function (obj) { return obj.user === data['addedFriend']['email']; });
            receiver = connected_users[obj];
            io.to(`${receiver['socket_id']}`).emit('youwereadded','You have been added to a room'); 

在组件方面,我在主要组件TS上有以下代码:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'public';
  socket: SocketIOClient.Socket;

  constructor(private _router: Router,
    private _httpService: HttpService){
      this.socket = io.connect('http://localhost:0000');
    };

  ngOnInit() {

    this.socket.on('youwereadded',function(){
      console.log("got you were added message")
    })
  }

}

我做错什么了吗?谁能帮忙吗? 谢谢!

0 个答案:

没有答案