From b6767f3b319c5b2595f008830a5d6d91175b7736 Mon Sep 17 00:00:00 2001 From: x ronger Date: Mon, 10 Aug 2020 00:44:27 +0800 Subject: [PATCH] :heavy_plus_sign: socket.io --- components/common/comment/main.vue | 5 +- io/index.js | 28 + nuxt.config.js | 1 + package-lock.json | 816 ++++++++++++++++++++++++++++- package.json | 3 +- pages/chats/_nickname.vue | 276 ++++++++++ pages/user/_nickname.vue | 12 +- plugins/socket.io.js | 8 + server/index.js | 20 + 9 files changed, 1156 insertions(+), 13 deletions(-) create mode 100644 io/index.js create mode 100644 pages/chats/_nickname.vue create mode 100644 plugins/socket.io.js diff --git a/components/common/comment/main.vue b/components/common/comment/main.vue index 0b850fa..fdc9911 100644 --- a/components/common/comment/main.vue +++ b/components/common/comment/main.vue @@ -76,9 +76,8 @@ + + diff --git a/pages/user/_nickname.vue b/pages/user/_nickname.vue index 43aafc9..13e35f3 100644 --- a/pages/user/_nickname.vue +++ b/pages/user/_nickname.vue @@ -11,6 +11,9 @@

{{user.nickname}}

+
+ 聊天 +
@@ -58,7 +61,8 @@ ...mapState({ user: state => state.user.data, articles: state => state.user.articles, - portfolios: state => state.user.portfolios + portfolios: state => state.user.portfolios, + oauth: state => state.oauth }) }, data() { @@ -75,6 +79,12 @@ }, handleToggleTab(key) { this.$set(this, 'activeTab', key); + }, + gotoChats() { + let _ts = this; + _ts.$router.push({ + path: `/chats/${_ts.user.nickname}` + }) } } } diff --git a/plugins/socket.io.js b/plugins/socket.io.js new file mode 100644 index 0000000..1b059d6 --- /dev/null +++ b/plugins/socket.io.js @@ -0,0 +1,8 @@ +import io from 'socket.io-client' +import apiConfig from '~/config/api.config' + +const socket = io(apiConfig.SOCKET, { + transports: ['websocket'] +}) + +export default socket diff --git a/server/index.js b/server/index.js index b47250d..bf12eae 100644 --- a/server/index.js +++ b/server/index.js @@ -1,6 +1,8 @@ const { Nuxt, Builder } = require('nuxt') +const http = require('http') const app = require('express')() +const socketio = require('socket.io') const isProd = (process.env.NODE_ENV === 'production') const port = process.env.PORT || 3000 @@ -8,6 +10,8 @@ const port = process.env.PORT || 3000 const config = require('./nuxt.config.js') config.dev = !isProd const nuxt = new Nuxt(config) +const server = new http.Server(app) +const io = socketio(server, { transports: ['websocket'] }) // 用 Nuxt.js 渲染每个路由 app.use(nuxt.render) @@ -26,3 +30,19 @@ function listen () { app.listen(port, '0.0.0.0') console.log('Server listening on `localhost:' + port + '`.') } + +// Socket.io +const messages = [] +io.on('connection', (socket) => { + socket.on('last-messages', function (fn) { + console.log('messages-server', messages); + fn(messages.slice(-50)) + }); + + socket.on('all', function (message) { + console.log('message-server', message); + messages.push(message) + socket.broadcast.emit('new-message', message) + }); + +})