Skip to content

Commit

Permalink
Merge pull request #3 from weaponsforge/websockets-ping-pong
Browse files Browse the repository at this point in the history
websocket server updates
  • Loading branch information
weaponsforge authored May 25, 2020
2 parents 617470c + 5e39893 commit 9a6768b
Show file tree
Hide file tree
Showing 14 changed files with 263 additions and 38 deletions.
4 changes: 3 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ REGISTER=register
BROADCAST=broadcast
LOGOUT=logout
ERROR=error
PING=ping

SERVER=server_msg
USER=user_msg
Expand All @@ -14,4 +15,5 @@ CODE=code
MESSAGE=message

SERVER_ADMIN=system
SERVER_PORT=3000
SERVER_PORT=3000
PING_TIMEOUT=30000
29 changes: 29 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Deploy to Heroku

on:
push:
branches:
- master

jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
env:
HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
HEROKU_EMAIL: ${{ secrets.HEROKU_EMAIL }}
HEROKU_APP: ${{ secrets.HEROKU_APP }}
steps:
- name: Checkout and Deploy
uses: actions/checkout@v1
- run: |+
cat >~/.netrc <<EOF
machine api.heroku.com
login $HEROKU_EMAIL
password $HEROKU_API_KEY
machine git.heroku.com
login $HEROKU_EMAIL
password $HEROKU_API_KEY
EOF
- run: heroku git:remote -a $HEROKU_APP
- run: git push heroku HEAD:refs/heads/master
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ The following software have been used for this project.
2. Windows 10 64-bit OS


### Demo

[https://socketchats.herokuapp.com/](https://socketchats.herokuapp.com/)


## Installation

1. Clone this repository.
Expand Down
2 changes: 1 addition & 1 deletion public/js/components/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const app = new Vue({
this.currentUser = data[MESSAGE][USERID]
this.code = data[MESSAGE][CODE]
}
} else {
} else if (data[ACTION] !== PING) {
this.messages.push(data)
}
}
Expand Down
15 changes: 14 additions & 1 deletion public/js/components/controlpanel/controlpanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,38 @@ Vue.component('controlpanel', {
post: ''
}
},
mounted () {
this.$refs.post.focus()
this.$refs.post.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
this.$refs.btnsend.click()
}
})
},
methods: {
submit () {
if (ChatWS.getUser()) {
ChatWS.sendMessage(this.post)
} else {
ChatWS.register(this.post)
}

this.post = ''
}
},
template: `
<div id="controlpanel" class="controlpanel">
<!-- User Post -->
<div class="panelitem postcontainer">
<input type="text" id="post" placeholder="Enter your message" v-model="post" />
<input type="text" id="post" placeholder="Enter your message"
v-model="post"
ref="post" />
</div>
<!-- Send Button -->
<div class="panelitem btnsubmitcontainer">
<button
ref="btnsend"
@click="submit()">Send
</button>
</div>
Expand Down
13 changes: 12 additions & 1 deletion public/js/components/register/register.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ Vue.component('register', {
messages: []
}
},
mounted () {
this.$refs.username.focus()
this.$refs.username.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
this.$refs.btnregister.click()
}
})
},
methods: {
submit () {
ChatWS.register(this.username)
Expand All @@ -22,9 +30,12 @@ Vue.component('register', {
<input
id="username"
v-model="username"
ref="username"
placeholder="Enter your username"
autocomplete="off" />
<button @click="submit()">Submit</button>
<button
ref="btnregister"
@click="submit()">Submit</button>
</div>
</div>`
})
88 changes: 76 additions & 12 deletions public/js/websocket-client.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
/**
* Establishes connection to the websocket server.
* Listens and sends for messages to and from the websocket server.
* Uses the browser's native WebSocket.
* Requires defines.js
*/
class WebsocketClient {
constructor () {
this.socket = new WebSocket(`ws://localhost:${SERVER_PORT}`)
this.socket = new WebSocket(`${window.location.origin.replace(/^http/, 'ws')}`)
this.user = null
this.isConnected = false

// DELETE
this.connectionTime = 0
this.interval = null

// Client to server ping
this.pingInterval = null
this.pingTimeout = PING_TIMEOUT
}

/**
Expand All @@ -17,34 +26,85 @@ class WebsocketClient {
initSocket (callback) {
this.socket.addEventListener('open', () => {
console.log('connected to server.')
this.pingStart()
this.isConnected = true
})

this.socket.addEventListener('message', (event) => {
const data = this.parseResponse(event.data)

if (data[ACTION] === REGISTER) {
switch (data[ACTION]) {
case REGISTER:
this.user = data[MESSAGE][USERID]
break
default:
// Reset ping
this.pingStart()
break
}

callback(data)
})

this.socket.addEventListener('close', (event) => {
clearInterval(this.interval)
clearInterval(this.pingInterval)
console.log('connection closed.')
console.log(`connection time: ${this.connectionTime}`)
})

this.socket.addEventListener('disconnect', (event) => {
clearInterval(this.pingInterval)
console.log('connection disconnected.')
console.log(event)
})

this.socket.onerror = function (event) {
clearInterval(this.pingInterval)
console.log(event)
alert(event.data)
}

// DELETE
this.interval = setInterval(() => {
this.connectionTime += 1
}, 1000)
}

pingStart () {
clearInterval(this.pingInterval)

// Ping server
this.pingInterval = setInterval(() => {
this.socket.send(this.createRequest({
[ACTION]: PING
}))
}, this.pingTimeout)
}

pingStop () {
clearInterval(this.pingInterval)
}

/**
* Send the text content of an html <input /> to the ws server.
* @param {String} message String text to broadcast
*/
sendMessage (message) {
this.socket.send(this.createRequest({
[ACTION]: BROADCAST,
[USERID]: this.user,
[MESSAGE]: message
}))
if (this.socket.readyState !== this.socket.OPEN) {
alert('Please reload your re-establish connection.')
return
}

try {
this.socket.send(this.createRequest({
[ACTION]: BROADCAST,
[USERID]: this.user,
[MESSAGE]: message
}))
} catch (err) {
alert(`${err.message}\nReload your browser to re-establish connection.`)
}
}

/**
Expand All @@ -53,13 +113,17 @@ class WebsocketClient {
*/
register (username) {
if (!username) {
return
throw new Error('Username required.')
}

this.socket.send(this.createRequest({
[ACTION]: REGISTER,
[USERID]: username
}))
try {
this.socket.send(this.createRequest({
[ACTION]: REGISTER,
[USERID]: username
}))
} catch (err) {
alert(`${err.message}\nReload your re-establish connection.`)
}
}

/**
Expand Down
13 changes: 11 additions & 2 deletions public/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ body, html {
border-bottom-right-radius: 0;
border: 3px solid #2286c3;
background-color: #ffffff;
width: 100%;
height: 100%;
overflow-y: auto;
}
Expand Down Expand Up @@ -134,7 +133,6 @@ body, html {

.controlpanel {
display: flex;
width: 100%;
height: 40px;
border-radius: 10px;
border: 3px solid #2286c3;
Expand Down Expand Up @@ -179,4 +177,15 @@ body, html {
background-color: transparent;
border-bottom-right-radius: 10px;
outline: none;
}

@media screen and (max-width: 768px) {
.registercontainer {
flex-direction: column;
}

.leftpanel {
height: 20%;
background-color: transparent;
}
}
6 changes: 5 additions & 1 deletion scripts/create-client-defines.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ try {
if (pair[0] === 'SERVER_PORT') {
return `const ${pair[0]} = ${process.env.PORT || pair[1]}`
} else {
return `const ${pair[0]} = '${pair[1]}'`
if (!isNaN(pair[1])) {
return `const ${pair[0]} = ${parseInt(pair[1])}`
} else {
return `const ${pair[0]} = '${pair[1]}'`
}
}
}).toString().replace(/,/g, '\n')

Expand Down
4 changes: 1 addition & 3 deletions server/utils.js → server/classes/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { KEYS } = require('./defines')
const { KEYS } = require('../defines')

class Utils {
/**
Expand All @@ -22,8 +22,6 @@ class Utils {
const g = Math.floor(Math.random() * (max - min + 1) + min)
const b = Math.floor(Math.random() * (max - min + 1) + min)
rgb = `rgba(${r}, ${g}, ${b}, 0.1)`

console.log(rgb)
} while (!rgb && userCodes.includes(rgb))

return rgb
Expand Down
Loading

0 comments on commit 9a6768b

Please sign in to comment.