-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketIONotes.js
78 lines (60 loc) · 2.17 KB
/
socketIONotes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// track individual socket status
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
const express = require('express');
const app = express();
// ...other middleware...
const server = app.listen(1337);
const io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on('alpha', function (data) {
// socket.emit will respond back to the socket client that triggered this 'alpha' listener
socket.emit('updateClient', { data: 5 });
});
socket.on('beta', function (data) {
// io.emit will message all socket clients
io.emit('updateAllClients', { data: 5 });
});
socket.on('gamma', function (data) {
// socket.broadcast will message all socket clients except the one that triggered the 'gamma' listener
socket.broadcast.emit('updateAllExceptOne', { data: 5 });
});
});
const express = require('express');
const app = express();
app.use(express.static(__dirname + "/public"));
const server = app.listen(1337);
const io = require('socket.io')(server);
var counter = 0;
io.on('connection', function (socket) { //2
socket.emit('greeting', { msg: 'Greetings, from server Node, brought to you by Sockets! -Server' }); //3
socket.on('thankyou', function (data) { //7
console.log(data.msg); //8 (note: this log will be on your server's terminal)
});
});
<html>
<head>
<title>Sockets</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type ="text/javascript">
$(document).ready(function (){
var socket = io(); //1
socket.on('greeting', function (data) { //4
console.log(data.msg); //5
socket.emit('thankyou', { msg: 'Thank you for connecting me! -Client' }); //6
});
})
</script>
</head>
<body>
<h1>Fun with sockets</h1>
</body>
</html>