diff options
-rw-r--r-- | public/scripts/main.js | 33 | ||||
-rw-r--r-- | views/index.pug | 2 |
2 files changed, 30 insertions, 5 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>`); + } } /** diff --git a/views/index.pug b/views/index.pug index 9afc2b3..3c70f14 100644 --- a/views/index.pug +++ b/views/index.pug @@ -8,7 +8,7 @@ block content section.nes-container.with-title h2.title Chat Window .containers - pre#incoming.nes-container.with-title + pre#messages.nes-container.with-title .form.nes-container.with-title .field label(for='message') Message |