journey socketio
Estimated reading time: 4 minutessocketio Relationship
server-side
var serverIO = require('socket.io')(9000);
serverIO.on('connection', (socket) => {
// fetch
socket.on('message', (response) => {
console.log(response.name)
});
// sent
socket.emit('post', {
title: 'data server to cilent',
like: 100
})
socket.on('disconnect', () => { });
});
client-side
var socket = io('http://localhost:9000');
socket.on('connect', () => {
socket.send('hi');
// sent
socket.emit('message',{
id: 1,
name: 'socket.io'
})
// fetch
socket.on('post', (response) => {
console.log(response.title)
});
});
emit cheetsheat
emit
// sending to sender-client only
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.emit('message', "this is a test");
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid (server-side)
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
// join to subscribe the socket to a given channel (server-side):
socket.join('some room');
// then simply use to or in (they are the same) when broadcasting or emitting (server-side)
io.to('some room').emit('some event'):
// leave to unsubscribe the socket to a given channel (server-side)
socket.leave('some room');
client others
var socket = io.connect("https://localhost:8082", {
query: 'key=nokey',
'reconnection limit': 10000,
'max reconnection attempts': Infinity,
reconnection: false,
upgrade: false,
rememberUpgrade: true,
transports: ['websocket']
});
socket .on('connect', function () {
socket.emit('name', 'vis.0');
socket.emit('authenticate', function () {});
});