mirror of
https://github.com/nuxt/nuxt.git
synced 2025-01-28 22:32:42 +00:00
Start refactoring sockets example
This commit is contained in:
parent
a870896c67
commit
896f80d59f
24
examples/with-sockets/io/index.js
Normal file
24
examples/with-sockets/io/index.js
Normal 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)
|
||||
})
|
||||
});
|
||||
}
|
@ -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'
|
||||
}
|
||||
}
|
||||
|
@ -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) {
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user