-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
82 lines (60 loc) · 1.42 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
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
79
80
81
82
$(document).ready(function(){
// alert(123);
});
var clientWS = null;
var username = null;
function main()
{
username = $("#username").val();
if(!username)
{
swal("Username", "Insert a username!", "warning");
return;
}
$("#login").hide();
$("#chatroom").show();
clientWS = new WebSocket("ws://localhost:8080/chat");
clientWS.onopen = function (event) {
swal("Connected", "Connected successfully!", "success");
clientWS.send(JSON.stringify({
action: "login",
content: username
}));
};
clientWS.onerror = function (event) {
swal("Error", "Something happens!", "error");
};
clientWS.onclose = function (event) {
swal("Closed", "Your connection was closed!", "info");
$("#login").show();
$("#chatroom").hide();
};
clientWS.onmessage = function (event) {
console.log(event);
var message = JSON.parse(event.data);
if(message.action == "login")
{
$("#message-box").append("<p>" + message.content + " connected.</p>");
}
else if(message.action == "message")
{
var c = "alert-secondary";
if(username == message.username)
c = "alert-info";
$("#message-box").append("<div class='alert " + c + "'><p class='m-0'><b>" + message.username + ": </b>" + message.content + "</p><div>");
}
};
}
function sendMessage()
{
var msg = $("#message").val();
if(!msg)
{
return;
}
clientWS.send(JSON.stringify({
action: "message",
content: msg
}));
$("#message").val("");
}