0
votes

Building chat application with Reactjs nodejs and socket.io.

When I run this code, it connects to server. when i send message for example from chrome browser, I can see the message I sent but the other client in another browser is not getting any message.

All the messages sent are seen in the console log.

If I use socket.broadcast.emit() function, I cannot see the message that I sent but the other clients will see it and vice versa.

How do I solve this issue so that both client can send see and recieve messages to and from each other.

import React, { Component, Fragment } from "react";
import { render } from "react-dom";

import axios from 'axios';
import io from "socket.io-client";


class ChatReact extends React.Component {
  constructor(props) {
    super(props);

 this.state = {

 username: '',
 message: '',
 messages: []

};

 this.sendMessage = this.sendMessage.bind(this);
}


componentDidMount(){
this.socket = io('http://localhost:9090');

this.socket.on('connect',(data) => {
    this.socket.emit('joined', 'Hello World from client...');
 });

this.socket.on('acknowledge', function(data) {
        alert(data);
    });




        this.socket.on('response message', function(data){
            addMessage(data);
        });

        const addMessage = data => {
            console.log(data);
            this.setState({messages: [...this.state.messages, data]});
            console.log(this.state.messages);
        };


}


 sendMessage = ev => {
            ev.preventDefault();
            this.socket.emit('chat message', {
                author: this.state.username,
                message: this.state.message
            })
            this.setState({message: ''});

        }

  render() {
    return (
      <div >
        <div>

 <div className="messages">
                                    {this.state.messages.map(message => {
                                        return (
                                            <div>{message.author}: {message.message}</div>
                                        )
                                    })}
                                </div>





<h1> Testing Socket Io with Reactjs</h1>

 <div className="card-footer">
                                <input type="text" placeholder="Username" value={this.state.username} onChange={ev => this.setState({username: ev.target.value})} className="form-control"/>
                                <br/>
                                <input type="text" placeholder="Message" className="form-control" value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
                                <br/>
                                <button onClick={this.sendMessage} className="btn btn-primary form-control">Send</button>
                            </div>




        </div>

      </div>
    );
  }
}

here is the server response

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/chat.html');
});

io.on('connection', function(socket){
    console.log('a user connected now..');
    socket.on('joined', function(data) {
        console.log(data);
        socket.emit('acknowledge', 'Acknowledged');
    });
    socket.on('chat message', function(data){
socket.emit('response message', data);
        //socket.broadcast.emit('response message', data);
console.log(JSON.stringify(data));


    });
});

http.listen(9090, function(){
    console.log('listening on *:9090');
});
1
I think you need to make a few changes. First, replace var http = require('http').Server(app) by var server = require('http').createServer(app). Second repalce var io = require('socket.io')(http) by var io = require('socket.io')(server). I hope it will work - dnp1204
Still the same issue - Nancy Moore

1 Answers

0
votes

Use socket.io cheatsheet to understand who has to see the messages. "broadcast" clearly states to send messages to all clients except the sender. If you need to send a message for many users including the sender then better use the room method. Also take care of what instance are you using whether socket or io (instance of connection).

io.in('roomName').emit('acknowledge', 'Acknowledged')