Home > front end >  How to display a random number in Socket.io?
How to display a random number in Socket.io?

Time:05-18

I'm currently working on a project including Socket.io and building a chat application. I would like to send a message from the input after clicking the send button, which will display the message and also display a random dice number after pressing the other button.

So the problem with this code so far, is that when I pressed the button that should generate a random number just comes up blank.

I would be happy for any tip i can get to solve this!

index.html

<div id="messages"></div>
    <form id="send-container">
        <input type="text" id="inputMessage" placeholder="Aa">
        <button type="submit" id="send">Skicka meddelande</button>
        <button id="roll">Kasta tärningen</button>
    </form>

main.js

const socket = io();
const messageForm = document.getElementById('send-container');
const messageContainer = document.getElementById('messages')
const inputMessage = document.getElementById('inputMessage');
const rollDice = document.getElementById('roll');

const userName = prompt('Vänligen skriv ditt användarnamn.')
showMessages('Välkommen! Du är nu ansluten till chatten!')
socket.emit('new-connection', userName)

socket.on('message', data => {
    showMessages(`${data.userName}: ${data.message}`);
});

socket.on('throw-dice', data => {
    showMessages(`${data.userName}: ${data.throw-dice}`);
});

socket.on('connected', userName => {
    showMessages(`${userName} har anslutit till chatten`);
});

socket.on('disconnected', userName => {
    showMessages(`${userName} har lämnat chatten`);
});

messageForm.addEventListener('submit', e => {
    e.preventDefault();
    const message = inputMessage.value;
    showMessages(`Du: ${message}`)
    socket.emit('send-message', message)
    inputMessage.value = '';
})

rollDice.addEventListener('click', () => {
    const randomNumber = "Du kastade tärningen och fick värdet: "   Math.floor(Math.random() * 6)   1;
    socket.emit('throw-dice', randomNumber);
}, false)

function showMessages(message, randomNumber) {
    const diceElement = document.createElement('div')
    const messageElement = document.createElement('div')
    diceElement.innerText = randomNumber
    messageElement.innerText = message
    messageContainer.append(messageElement, diceElement);
}

server.js

const express = require("express");
const path = require('path');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
const port = 3000;

const user = {}

app.use(express.static(path.join(__dirname   '/public')));

io.on('connection', (socket) => {
    console.log(`User with id ${socket.id} joined to the chat!`);

    socket.on('new-connection', userName => {
        user[socket.id] = userName
        socket.broadcast.emit('connected', userName)
    })

    socket.on('send-message', message => {
        socket.broadcast.emit('message', {
            message: message,
            userName: user[socket.id]
        })
    });

    socket.on('throw-dice', randomNumber => {
        socket.broadcast.emit('randomNumber', {
            message: randomNumber,
            userName: user[socket.id]
        })
    });

    socket.on('disconnect', () => {
        socket.broadcast.emit('disconnected', user[socket.id])
        delete user[socket.id]
        console.log(`User with id ${socket.id} left the chat!`);
    });
});

server.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}/`);
});

CodePudding user response:

You emit your broadcast with "randomNumber" event id (from the server), while expecting to receive a "throw-dice" event (on the client, main.js). Change one of these to match the other and I believe it should work fine

  • Related