简体   繁体   中英

simple node client server communication not working using express and socket.io

I'm trying to write a simple client server application.

That's the HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script src="client.js"></script>
</body>

</html>

server.js file:

const express = require('express');
const app = express();
const port = 3000;
const server = app.listen(port);
const io = require('socket.io')(server);

app.get('/', (req, res) => {
  res.send('Hello World!');
});

io.on('connection', (socket) => {
    console.log('a user connected');
});

client.js file:

const socket = io('https://localhost:3000/');

At this moment if I start the server by typing node server on the terminal and I open the HTML file using the LiveServer vs extension, the console doesn't show the text a user connected , it also returns an error which is:

GET https://localhost:3000/socket.io/?EIO=4&transport=polling&t=NdZ4wOd net::ERR_SSL_PROTOCOL_ERROR

I don't know what I'm doing wrong.

In the client.js file you could try const socket = io.connect(); and I'm not sure but i think <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script> Should be in the header but i could be wrong about that.

**Make Changes In Your Server File **

const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
const server = app.listen(port);
const io = require('socket.io')(server);

app.get('/', (req, res) => {
  res.send('Hello World!');
});

io.on('connection', (socket) => {
    console.log('a user connected');
});

Install cors npm package before starting your server using npm i cors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM