node socket.io code example
Example 1: install socket.io
npm i socket.io
Example 2: create a web server node js w socket.io
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
});
http.listen(3000, () => {
});
Example 3: js socket.emit
const socket = io('ws://localhost:3000');
socket.on('connect', () => {
socket.send('Hello!');
socket.emit('salutations', 'Hello!', { 'mr': 'john' }, Uint8Array.from([1, 2, 3, 4]));});
socket.on('message', data => {
console.log(data);
});
socket.on('greetings', (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
Example 4: socket..io
<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
Example 5: socket io node js
npm install socket.io
Example 6: socket io
npm install --save socket.io