1<script src="/socket.io/socket.io.js"></script>
2<script>
3 const socket = io();
4</script>
1const express = require("express");
2const http = require("http");
3const socketIo = require("socket.io");
4const port = process.env.PORT || 8001;
5const index = require("./routes/index");
6const app = express();
7app.use(index);
8const server = http.createServer(app);
9const io = socketIo(server); // < Interesting!
10const getApiAndEmit = "TODO";
1const socket = io('ws://localhost:3000');
2socket.on('connect', () => {
3 // either with send()
4 socket.send('Hello!');
5 // or with emit() and custom event names
6 socket.emit('salutations', 'Hello!', { 'mr': 'john' }, Uint8Array.from([1, 2, 3, 4]));});
7// handle the event sent with socket.send()
8socket.on('message', data => {
9 console.log(data);
10});
11// handle the event sent with socket.emit()
12socket.on('greetings', (elem1, elem2, elem3) => {
13 console.log(elem1, elem2, elem3);
14});
1const 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');});
1const app = require("express")();const httpServer = require("http").createServer(app);const options = { /* ... */ };const io = require("socket.io")(httpServer, options);io.on("connection", socket => { /* ... */ });httpServer.listen(3000);// WARNING !!! app.listen(3000); will not work here, as it creates a new HTTP server