-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.html
114 lines (88 loc) · 2.77 KB
/
chat.html
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>Chat Now</title>
</head>
<body>
</body>
<div class="header"><a id="username">....</a><span class="online">Online</span></div>
<div class="chats"></div>
<div class="sendbox">
<input type="text" name="message" id="message" required />
<button type="button" onClick="sendMessage()">Send</button>
</div>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"
integrity="sha512-2RDFHqfLZW8IhPRvQYmK9bTLfj/hddxGXQAred2wNZGkrKQkLGj8RCkXfRJPHlDerdHHIzTFaahq4s/P4V6Qig=="
crossorigin="anonymous"
></script>
<script>
const message_field = $("#message");
const name = "Tanmoy Sarkar";
var messageRecieved = false;
const socket = io("http://localhost:3000",{
reconnectionDelayMax: 10000,
autoConnect : true,
});
socket.on("connect", () => {
console.log(socket.id);
if(!messageRecieved){
load50();
messageRecieved = true;
}
});
socket.on("oldmesssagesrecieved",function(data){
// const j = data.docs.length-1;
console.log(data);
$.each(data, function(i) {
// if(data.docs[j-i].send_by == currentUser){
// addMessage("to",data.docs[j-i].content);
// }
// if(data.docs[j-i].send_by == recievedUser){
// addMessage("from",data.docs[j-i].content);
// }
addMessage("from",data[i].content)
});
$(".chats").scrollTop($(".chats")[0].scrollHeight);
});
socket.on("newmessage", function ({content, sendBy}) {
addMessage("from", `${content} ${sendBy}`);
console.log(content);
});
function load50(){
socket.emit("oldmessages",{
"page" : 0,
"limit" : 10
})
}
function sendMessage() {
var message = message_field.val().trim();
if (message != "") {
message_field.val("");
addMessage("to", message);
socket.emit("livemessage", {"content" : message,"name": name});
}
}
function addMessage(user, message) {
if (user == "to") {
$(`<div class="to">
<div class="contentto">${message}</div>
</div>`).appendTo($(".chats"));
}
if (user == "from") {
$(`<div class="from">
<div class="contentfrom">${message}</div>
</div>`).appendTo($(".chats"));
}
}
</script>
</html>