-
Notifications
You must be signed in to change notification settings - Fork 14
/
chat.js
49 lines (39 loc) · 1.17 KB
/
chat.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
var syscalls = require('syscalls')
var loop = require('./loop')
var acceptFd = syscalls.socket(syscalls.AF_INET, syscalls.SOCK_STREAM, 0)
syscalls.fcntl(acceptFd, syscalls.F_SETFL, syscalls.O_NONBLOCK)
syscalls.bind(acceptFd, 3000, "0.0.0.0")
syscalls.listen(acceptFd, 100)
var users = [] // FDs
function accept() {
var userFd = syscalls.accept(acceptFd)
users.push(userFd)
console.log("User connected on FD: " + userFd)
syscalls.write(userFd, "Welcome!\n")
return userFd
}
function readAndBroadcastMessage(senderFd) {
var msg = syscalls.read(senderFd, 1024)
// Read w/ a 0 byte string == connection closed
if (msg.length == 0) {
disconnect(senderFd)
return;
}
// Send the message to all connected users
users.forEach(function(receiverFd) {
if (receiverFd != senderFd) syscalls.write(receiverFd, "user " + senderFd + "> " + msg)
})
}
function disconnect(fd) {
console.log("User disconnect on FD: " + fd)
syscalls.close(fd)
users.splice(users.indexOf(fd), 1)
loop.remove(fd, 'read')
}
loop.on(acceptFd, 'read', function() {
var userFd = accept()
loop.on(userFd, 'read', function() {
readAndBroadcastMessage(userFd)
})
})
loop.run()