socket.io in node js code example
Example 1: 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 2: socket io nodejs
const express = require('express');const app = express();const http = require('http');const server = http.createServer(app);const { Server } = require("socket.io");const io = new Server(server);app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html');});io.on('connection', (socket) => { console.log('a user connected');});server.listen(3000, () => { console.log('listening on *:3000');});
Example 3: socket io node js
npm install socket.io
Example 4: socket.io doc
const socket = new WebSocket('ws://localhost:3000');socket.onopen(() => { socket.send('Hello!');});socket.onmessage(data => { console.log(data);});