socket.broadcast.to()不会发送给客户端

时间:2019-06-06 23:06:05

标签: javascript reactjs express socket.io

我无法使“ addMessage”发射器到达客户端。所有其他发射器都在工作。我期望console.log(addMessage在客户端上触发)触发,但是不会。任何帮助,将不胜感激。我已经在这件小事上停留了几个小时。

这是客户

import React, { Component } from 'react';
import io from 'socket.io-client';
import axios from 'axios';
import { Link } from 'react-router-dom'
import { withRouter } from 'react-router';
//5002
const socketURL="http://localhost:3000";
class ChatRoom extends Component {
  constructor(props){
    super(props);
    this.state = {
      messages: [],
      socket: null,
      message: '',
      users: [],
      id:this.props.match.params.id,
      userId: this.props.match.params.userId
    }
    this.onChange = this.onChange.bind(this);
    this.onSubmit=this.onSubmit.bind(this);
      this.initSocket();
      this.state.id = this.props.match.params.id;
  }

  componentWillMount(){
    console.log('this si the user id', this.state.userId);
  }

  initSocket = () => {
    const socket = io('http://127.0.0.1:5002', {
  transports: ['websocket'], jsonp: false });
  socket.connect();
  socket.on('connect', () => {
    this.setState({socket: socket});
    this.state.socket.emit('join', this.state.id, this.state.userId);
    this.state.socket.on('updateUsersList', (user)=> {
      console.log('firing here');
      this.setState({users: [...this.state.users, user]})
    });
    this.state.socket.on('addMessage', (message)=>{
      console.log('addmessage firing on client');
        this.setState({messages: [...this.state.messages, message]}, ()=> {
          console.log('a message was added');
        })
    });
  });
}

  componentDidUpdate(){
  }

  onSubmit(e) {
   e.preventDefault();
   this.state.socket.emit('newMessage', this.state.id, this.state.message);
   }


 onChange(e){
  this.setState({[e.target.name]: e.target.value});
}

  render() {
    return (
      <div className="App">
      <h1>In a room</h1>
      <form onSubmit={this.onSubmit}>
       <label>
         Name:
         <input type="text" name="message" onChange={this.onChange} value={this.state.message}/>
       </label>
       <input type="submit" value="Submit" />
     </form>
      </div>
    );
  }
}

export default ChatRoom;

这是套接字文件

var Room = require('./modelHelpers/roomHelper');

exports = module.exports = function(io) {
  //Set Listeners
    io.on('connection', function(socket) {

        // Create a new room
        socket.on('createRoom', function(title) {
      console.log('this is the title on the server', title);
            Room.findOne({'title': new RegExp('^' + title + '$', 'i')}, function(err, room){
                if(err) throw err;
                if(room){
                    socket.emit('updateRoomsList', { error: 'Room title already exists.' });
                } else {
                    Room.create({
                        title: title
                    }, function(err, newRoom){
                        if(err) throw err;
                        socket.emit('updateRoomsList', newRoom);
                        socket.broadcast.emit('updateRoomsList', newRoom);
                    });
                }
            });
        });


    // When a new message arrives
    socket.on('newMessage', function(roomId, message) {
      console.log('newMessage is being fired');
      console.log('here is the roomId', roomId);
      console.log('here is the message', message);
      socket.join(roomId);
      // No need to emit 'addMessage' to the current socket
      // As the new message will be added manually in 'main.js' file
      // socket.emit('addMessage', message);

      socket.broadcast.to(roomId).emit('addMessage', message);
    });


    ///
    socket.on('join', function(roomId, userId) {
      console.log('join is firing');
            Room.findById(roomId, function(err, room){
                if(err) throw err;
                if(!room){
                    // Assuming that you already checked in router that chatroom exists
                    // Then, if a room doesn't exist here, return an error to inform the client-side.
                    socket.emit('updateUsersList', { error: 'Room doesnt exist.' });
                } else {
                    // Check if user exists in the session

                    Room.addUser(room, userId, socket,  function(err, newRoom){

                        // Join the room channel
                        socket.join(newRoom.id);

                        Room.getUsers(newRoom, userId, socket, function(err, users, cuntUserInRoom){
                            if(err) throw err;

                            // Return list of all user connected to the room to the current user
                            socket.emit('updateUsersList', users, true);

                            // Return the current user to other connecting sockets in the room
                            // ONLY if the user wasn't connected already to the current room
                            if(cuntUserInRoom === 1){
                                socket.broadcast.to(newRoom.id).emit('updateUsersList', users[users.length - 1]);
                            }
                        });
                    });
                }
            });
    });

  socket.on('disconnect', function() {
            // Check if user exists in the sessi
            // Find the room to which the socket is connected to,
            // and remove the current user + socket from this room
            Room.removeUser(socket, function(err, room, userId, cuntUserInRoom){
                if(err) throw err;

                // Leave the room channel
                socket.leave(room.id);

                // Return the user id ONLY if the user was connected to the current room using one socket
                // The user id will be then used to remove the user from users list on chatroom page
                if(cuntUserInRoom === 1){
                    socket.broadcast.to(room.id).emit('removeUser', userId);
                }
            });
        });
    });
}

0 个答案:

没有答案