chat sender dont receive own messages

This commit is contained in:
lenovo
2022-11-30 17:52:39 +01:00
parent 55f77d2259
commit 9aec5bd015
7 changed files with 36 additions and 20 deletions

View File

@@ -11,3 +11,4 @@ next time :
anytime :
nodemon server
- [ ] don't send message to oneself

View File

@@ -50,6 +50,7 @@
<script src="./chat_submit_msg.js"></script>
<script src="./chat_receive_msg.js"></script>
<script src="./chat_add_msg.js"></script>
</body>
</html>

View File

@@ -0,0 +1,17 @@
const add_new_message = (message, from = "others") => {
const div_thread = document.getElementById('msg_thread');
console.log("received message:");
console.log(`[${message}]`);
div_thread.appendChild(build_new_message(message, from));
}
const build_new_message = (message, from) => {
const p = document.createElement("p");
p.classList.add(from);
p.appendChild(document.createTextNode(message));
return p;
}

View File

@@ -1,20 +1,5 @@
socket.on('chat_message', ({ data }) => {
handle_new_message(data);
add_new_message(data);
});
const handle_new_message = (message) => {
const div_thread = document.getElementById('msg_thread');
console.log("received message:");
console.log(`[${message}]`);
div_thread.appendChild(build_new_message(message));
}
const build_new_message = (message) => {
const p = document.createElement("p");
p.appendChild(document.createTextNode(message));
return p;
}

View File

@@ -12,7 +12,9 @@ const submit_new_message = () => {
console.log(`[${msg}]`);
console.log(msg.length);
if (msg.length > 0)
if (msg.length > 0) {
socket.emit('chat_message', { data: msg });
add_new_message(msg, "me");
}
}

View File

@@ -12,8 +12,16 @@
.chat_box #msg_thread p {
white-space: pre-wrap;
margin: 5px auto 5px 0px;
margin: 5px auto;
padding: 5px;
border-radius: 5px;
}
.chat_box #msg_thread p.others {
margin-left: 0px;
background-color: rgb(210, 210, 210);
}
.chat_box #msg_thread p.me {
margin-right: 0px;
background-color: rgb(210, 110, 10);
}

View File

@@ -11,6 +11,7 @@ const { Server } = require("socket.io");
// https://socket.io/docs/v4/handling-cors/
const io = new Server(server, {
cors: {
// change this for the real front origin
origin: "*"
}
});
@@ -24,7 +25,7 @@ const io = new Server(server, {
// console.log(req.headers);
//})
io.on('connection', function (socket) {
io.on('connection', (socket) => {
console.log('a user is connected');
@@ -34,7 +35,8 @@ io.on('connection', function (socket) {
socket.on('chat_message', function (msg) {
console.log('message received: ' + msg);
io.emit('chat_message', msg);
socket.broadcast.emit('chat_message', msg);
//io.emit('chat_message', msg);
})
});