Start refactoring sockets example

This commit is contained in:
Sébastien Chopin 2017-07-10 09:03:18 +02:00
parent a870896c67
commit 896f80d59f
4 changed files with 28 additions and 6 deletions

View File

@ -0,0 +1,24 @@
module.exports = function () {
const server = require('http').createServer(this.nuxt.renderer.app)
const io = require('socket.io')(server)
// overwrite nuxt.listen()
this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve))
// close this server on 'close' event
this.nuxt.plugin('close', () => new Promise((resolve) => server.close(resolve)))
// Add `socket.io-client` in vendor
this.addVendor('socket.io-client')
// Add socket.io events
let messages = []
io.on('connection', (socket) => {
socket.on('last-messages', function (fn) {
fn(messages.slice(-50))
});
socket.on('send-message', function (message) {
messages.push(message)
socket.broadcast.emit('new-message', message)
})
});
}

View File

@ -1,14 +1,12 @@
module.exports = {
build: {
vendor: ['socket.io-client']
},
head: {
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' }
]
},
modules: ['~/io'],
env: {
HOST_URL: process.env.HOST_URL || 'http://localhost:3000'
WS_URL: process.env.WS_URL || 'http://localhost:3000'
}
}

View File

@ -14,7 +14,7 @@
</template>
<script>
import socket from '~plugins/socket.io.js'
import socket from '~/plugins/socket.io.js'
export default {
asyncData (context, callback) {

View File

@ -1,4 +1,4 @@
import io from 'socket.io-client'
const socket = io(process.env.HOST_URL)
const socket = io(process.env.WS_URL)
export default socket