-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.js
68 lines (54 loc) · 1.6 KB
/
client.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
var socket = io.connect('http://localhost');
var user;
// chat message received
socket.on('message', function (msg) {
addMessage(msg);
});
// user list
socket.on('users', function (users) {
for (var i = 0; i < users.length; i++)
addUser(users[i]);
});
// new user joined
socket.on('new-user', function (user) {
$('#chat-log').append('<li>' + user.name + ' joined</li>');
addUser(user);
});
// disconnect
socket.on('disconnect', function (user) {
if (user != null) {
$('#chat-log').append('<li>' + user.name + ' left</li>');
$('#user-' + user.name).fadeOut('fast');
}
});
$(function () {
$('.modal').modal('show');
// join the chat
$('#connect').click(function () {
user = { name: $('#name').val() };
socket.emit('join', user);
});
// send a message
$('#msg').keypress(function (event) {
if (event.which == 13) {
var msg = { user: user.name, text: $(this).val() };
socket.emit('message', msg);
addMessage(msg);
$('#msg').val('');
return false;
}
});
});
function addUser(user) {
$('#users').append('<li id="user-' + user.name + '">' + user.name + '</li>');
}
function addMessage(msg) {
console.log(msg);
msg.text = linkifyUrls(msg.text);
$('#chat-log').append('<li>' + msg.user + ': ' + msg.text + '</li>')
.scrollTop($(this).height())
}
function linkifyUrls(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp, '<a target="_blank" href="$1">$1</a>');
}