Home > database >  How can I create more than one message in a Socket.io chat app?
How can I create more than one message in a Socket.io chat app?

Time:09-10

I'm building a dummy chat app to know how socket.io works (with react and node. Everything seems to work fine except that socket io emits more than one message.

It looks like for each character I type when then I press on submit it emits the message multiplying the total of characters per 2.

How can I solve this?

Thank you!

Client

import React from "react";
import { useState } from "react";
import { io } from "socket.io-client";

const App = () => {

  const socket = io("http://localhost:5000");
  const [input, setInput] = useState("");

  const handleChange = (e) => {
    setInput(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    socket.emit("chat-message", input);
  };

  socket.on("chat-message", (msg) => {
    console.log(msg);
  });

  return (
    <div className="App">
      <h1>Chat</h1>
      <form onSubmit={handleSubmit}>
        <input onChange={handleChange} type="text" id="input" />
        <button type="submit">Send</button>
      </form>
      <div id="messages">

      </div>
    </div>
  );
};
export default App;

Server

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

const io = require('socket.io')(server, {
    cors: {
        origin: '*',
    }
});

io.on('connection', (socket) => {
    socket.on('chat-message', (msg) => {
        io.emit('chat-message', msg);
    })
});

server.listen(5000, () => {
  console.log('listening on: 5000');
});

CodePudding user response:

Because you are getting message twice from client and the server. It goes like this

  1. you send(emit) message from client onto "chat-message"
  2. then your client responds to socket.on("chat-message") and prints it once
  3. your server responds to socket.on('chat-message') and emits it back to client
  4. client react to re emitted message from server and prints again

CodePudding user response:

Can you once try this code?

//client side changes
 const handleSubmit = (e) => {
    e.preventDefault();
    socket.emit("chat-message", input);
  };

  socket.on("receive-message", (msg) => {
    console.log(msg);
  });
//server side changes
io.on('connection', (socket) => {
    socket.on('chat-message', (msg) => {
        io.emit('receive-message', msg);
    })
});

  • Related