socket io/socket.io.js code example

Example 1: socket io script

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
</script>

Example 2: js socket.emit

const socket = io('ws://localhost:3000');
socket.on('connect', () => {  
  // either with send()  
  socket.send('Hello!');
  // or with emit() and custom event names  
  socket.emit('salutations', 'Hello!', { 'mr': 'john' }, Uint8Array.from([1, 2, 3, 4]));});
// handle the event sent with socket.send()
socket.on('message', data => {
  console.log(data);
});
// handle the event sent with socket.emit()
socket.on('greetings', (elem1, elem2, elem3) => {
  console.log(elem1, elem2, elem3);
});

Example 3: socket..io

<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>

Example 4: socket io

npm install socket.io

Example 5: socket io

npm install --save socket.io

Example 6: socket io

const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
  client.on('event', data => { /* … */ });
  client.on('disconnect', () => { /* … */ });
});
server.listen(3000);

Tags: