-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
64 lines (50 loc) · 1.96 KB
/
app.js
File metadata and controls
64 lines (50 loc) · 1.96 KB
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
var app = require('express')();
var server = require('http').createServer(app);
// http server를 socket.io server로 upgrade한다
var io = require('socket.io')(server);
// localhost:3000으로 서버에 접속하면 클라이언트로 index.html을 전송한다
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// connection event handler
// connection이 수립되면 event handler function의 인자로 socket인 들어온다
io.on('connection', function(socket) {
// 접속한 클라이언트의 정보가 수신되면
socket.on('login', function(data) {
console.log('Client logged-in:\n name:' + data.name + '\n userid: ' + data.userid);
// socket에 클라이언트 정보를 저장한다
socket.name = data.name;
socket.userid = data.userid;
// 접속된 모든 클라이언트에게 메시지를 전송한다
io.emit('login', data.name );
});
// 클라이언트로부터의 메시지가 수신되면
socket.on('chat', function(data) {
console.log('Message from %s: %s', socket.name, data.msg);
var msg = {
from: {
name: socket.name,
userid: socket.userid
},
msg: data.msg
};
// 메시지를 전송한 클라이언트를 제외한 모든 클라이언트에게 메시지를 전송한다
socket.broadcast.emit('chat', msg);
// 메시지를 전송한 클라이언트에게만 메시지를 전송한다
// socket.emit('s2c chat', msg);
// 접속된 모든 클라이언트에게 메시지를 전송한다
// io.emit('s2c chat', msg);
// 특정 클라이언트에게만 메시지를 전송한다
// io.to(id).emit('s2c chat', data);
});
// force client disconnect from server
socket.on('forceDisconnect', function() {
socket.disconnect();
})
socket.on('disconnect', function() {
console.log('user disconnected: ' + socket.name);
});
});
server.listen(3000, function() {
console.log('Socket IO server listening on port 3000');
});