user12517139
user12517139

Reputation:

Socket.io and express ERR_CONNECTION_REFUSED error with Chat app

I'm following a tutorial about making a rock paper sissors game with a chat using socket.io and express. I'm only making the chat. But I'm getting an error that the person in the tutorial isn't getting. I don't know how to fix it. I've search google but could only find very complicated solutions.

The error that I get when I try to send a message is 'ERR_CONNECTION_REFUSED'. Here is my code:

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat</title>
</head>
<body>
    <div id="chatWrapper">
        <ul id="chatUl"></ul>
    </div>
    <div class="buttons">
        <form id="chatForm">
            <input id="chat"/>
            <button id="verstuur">Verstuur</button>
        </form>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script src="client.js"></script>
</body>
</html>

Server.js

const http = require('http');
const express = require('express');
const socketio = require('socket.io');

const app = express();

const clientPath = `${__dirname}/../client`;
console.log(`Static van ${clientPath}`);

app.use(express.static(clientPath));

const server = http.createServer(app);

const io = socketio(server);

io.on('connection', (sock) => {
    console.log("Iemand is verbonden");
    sock.emit('message', "Hoi, je bent verbonden!");

    sock.on('message', () => {
        io.emit('message', text);
    });
});

server.on('error', (err) => {
    console.error("Server fout: " + err);
});

server.listen(8080, () => {
    console.log('Chat opgestard op 8080');
});

Client.js

const writeEvent = (text) => {
    // <ul> element
    const parent = document.querySelector('#chatUl');

    // <li> element
    const el = document.createElement('li');
    el.innerHTML = text;

    parent.appendChild(el);
};

const onFormSubmitted = (e) => {
    e.preventDefault();

    const input = document.querySelector('#chat');
    const text = input.value;
    input.value = '';

    sock.emit('message', text);
};

writeEvent('Welkom bij de chat!');

const sock = io();
sock.on('message', writeEvent);

document
    .querySelector('#chatForm')
    .addEventListener('submit', onFormSubmitted);

Any help?

ps. The tutorial that I am following: https://www.youtube.com/watch?reload=9&v=xVcVbCLmKew
And sorry for bad English

Upvotes: 0

Views: 83

Answers (1)

BatSwen
BatSwen

Reputation: 145

You just forgot the formal parameter of a function (server.js):

io.on('connection', (sock) => {
    console.log("Iemand is verbonden");
    sock.emit('message', "Hoi, je bent verbonden!");

    sock.on('message', (/* variable here*/ text) => {
        io.emit('message', text);
    });
});

Also check the path to your files. Is "${__dirname}/../client" correct?

Upvotes: 0

Related Questions