Hello world with socket messages.
suggest changeInstall node modules
npm install express
npm install socket.io
Node.js server
const express = require('express');
const app = express();
const server = app.listen(3000, function () {
console.log("Socket.io Hello World server started!");
});
const io = require('socket.io')(server);
io.on('connection', (socket) => {
//console.log("Client connected!");
socket.on('message-from-client-to-server', (msg) => {
console.log(msg);
})
socket.emit('message-from-server-to-client', 'Hello World!');
});
Browser client. Load Socket.IO's client from the same server so the major versions match. npm install socket.io today is 4.x, which does not speak to the old 1.4 CDN build.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World with Socket.io</title>
</head>
<body>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io("http://localhost:3000");
socket.on("message-from-server-to-client", function(msg) {
document.getElementById('message').innerHTML = msg;
});
socket.emit('message-from-client-to-server', 'Hello World!');
</script>
<p>Socket.io Hello World client started!</p>
<p id="message"></p>
</body>
</html>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents