aboutsummaryrefslogtreecommitdiffhomepage
path: root/public
diff options
context:
space:
mode:
authorMarvin Borner2019-01-22 22:28:56 +0100
committerMarvin Borner2019-01-22 22:28:56 +0100
commit4980f79caa07d8c2ec878ceceba6e846679a0ad1 (patch)
treef87bc38d37fdb8daf28f8304c8a4e7dba8291c2e /public
parent3b7fbc8893bea720efea29164de5ee921e9b2b9f (diff)
Working bidirectional chat (needs some polishing though)
Diffstat (limited to 'public')
-rw-r--r--public/scripts/main.js33
1 files changed, 29 insertions, 4 deletions
diff --git a/public/scripts/main.js b/public/scripts/main.js
index ee63357..75fae1b 100644
--- a/public/scripts/main.js
+++ b/public/scripts/main.js
@@ -1,5 +1,4 @@
const $ = require('jquery');
-const util = require('util');
const nanoid = require('nanoid');
let connectedUserId, connectedUser;
@@ -8,9 +7,17 @@ const peer = new Peer(userId, {host: '127.0.0.1', port: 4242, path: '/', debug:
// Peer events
peer.on('open', id => console.log('[LOG] Your ID is', id));
-peer.on('connection', conn => console.log('[LOG] Connected with', conn.peer));
peer.on('error', err => console.error(err));
+peer.on('connection', conn => {
+ connectedUser = conn;
+ console.log('[LOG] Connected with', conn.peer);
+ conn.on('data', message => receivedMessage(message));
+});
+/**
+ * Connects to an user via his id
+ * @param id
+ */
function connect(id) {
const connectionId = nanoid();
console.log('[LOG] Connecting to', id);
@@ -20,16 +27,34 @@ function connect(id) {
// setup listener
connectedUser.on('open', () => {
- connectedUser.send('Hi!');
// TODO: Activate chat or sth
});
- connectedUser.on('data', data => console.log('[LOG] Received data', data));
+ connectedUser.on('data', message => receivedMessage(message))
}
+/**
+ * Sends a message to the user with which you're currently connected
+ * @param message
+ */
function sendMessage(message) {
console.log(`[LOG] Sending message ${message} to ${connectedUserId}`);
connectedUser.send(message);
+ receivedMessage(message, true);
+}
+
+/**
+ * Renders the incoming messages
+ * @param message
+ * @param self
+ */
+function receivedMessage(message, self = false) {
+ if (self) {
+ $('#messages').append(`<span style="color: green">${message}</span><hr>`);
+ } else {
+ $('#user_id').val(connectedUserId); // TODO: WTH DOESNT THIS WORK LOL
+ $('#messages').append(`${message}<hr>`);
+ }
}
/**