├── .babelrc ├── .editorconfig ├── .eslintignore ├── .gitignore ├── README.md ├── build ├── build.js ├── dev-client.js ├── dev-server.js ├── utils.js ├── webpack.base.conf.js ├── webpack.dev.conf.js └── webpack.prod.conf.js ├── config ├── dev.env.js ├── index.js ├── prod.env.js └── test.env.js ├── index.html ├── package.json ├── server ├── index.js └── package.json ├── src ├── App.vue ├── api │ └── client.js ├── assets │ ├── 1.jpg │ └── logo.png ├── components │ ├── ChatBody.vue │ ├── ChatFoot.vue │ ├── ChatHead.vue │ ├── GroupInfo.vue │ ├── GroupInfoBody.vue │ ├── GroupInfoHead.vue │ ├── OtherMsg.vue │ ├── SelfMsg.vue │ ├── SystemMsg.vue │ ├── login.vue │ └── util │ │ └── dialog.vue ├── main.js ├── router │ └── index.js └── util │ └── index.js ├── static └── .gitkeep └── test └── unit ├── .eslintrc ├── index.js ├── karma.conf.js └── specs └── Hello.spec.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015", "stage-2"], 3 | "plugins": ["transform-runtime"], 4 | "comments": false 5 | } 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | config/*.js 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log 5 | selenium-debug.log 6 | test/unit/coverage 7 | test/e2e/reports 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 基于vue和websocket的多人在线聊天室 2 | * author: So 3 | ------ 4 | 5 | 最近看到一些关于websocket的东西,就决定写一个在线聊天室尝试一下。最终决定配合vue来写,采用了官方的vue脚手架vue-cli和官方的router,在本例中呢,我是用了CHAT这个对象来存储app的数据的,但后来一想,虽然项目很小,但如果用官方的vuex会更好,方便以后扩展,比如可以加上私信功能,可以在对方不在线的时候缓存发送的消息,这些都是可以的。(现在比较尴尬的就是,我把聊天室写好放到公众号号redream里,但是很少有人会同时在线,所以你会经常发现你进去的时候只有你一个人,就导致群聊不起来) 6 | 7 | ### 1.好吧,先来看一下我们的效果图 8 | ![login](http://item.redream.cn/chat/0.jpg ) 9 | ![login](http://item.redream.cn/chat/447.jpg ) 10 | ![login](http://item.redream.cn/chat/445.jpg ) 11 | 详细见[redream文章](http://mp.weixin.qq.com/s?__biz=MzAwMjAzNDU1NQ==&mid=2650166098&idx=1&sn=8ea7fda842823a1a0528742589f9f238&chksm=82d26d46b5a5e4503e830de7f41469b5fe93a08058bf839838f13597914037230ea114a57f3a#rd) 12 | 13 | ### 2.用到的一些东西 14 | > * nodejs node服务器运行环境 15 | > * express 搭建node服务器 16 | > * websocket 本例核心,推送服务器消息到所有人 17 | > * socketio websocket第三方库 18 | > * vue + router 视图层双向数据绑定框架,用来简化开发、组件化开发的 19 | > * es6语法 就是好用简洁哈哈 20 | > * https 因为像websocket和很多h5的新功能,浏览器为了安全起见都仅支持https下开发 21 | 关于nodejs搭建express服务器可以看[这里](http://www.plhwin.com/2014/05/28/nodejs-socketio/)我就是在这里学的,代码里也借鉴了很多,关于搭建https服务器就不简介了,内容太多,推荐阿里云一年的免费证书,可以访问[我的站点](https://node.redream.cn)查看 22 | 23 | ### 3.代码架构简介 24 | * server里是需要运行在node服务器上的js文件,监听websocket连接 25 | * src/api/client是客户端连接服务器的核心js 26 | * src/components下是页面的组件。我分成了三大部分,login组件(登录页面),chat组件(聊天页面),groupinfo组件(群信息页面),其实是单页应用,反应速度更快,接近原生app,只不过用router联系在了一起。像chat组件,又又head、body、foot组件组成,组件化是很好的习惯和架构方式,条理清晰,而且在大项目里很多可以复用。 27 | 具体都在代码了,大家可以下载下来在本地跑一跑。 28 | 29 | ### 4.运行代码 30 | * install dependencies 31 | > npm install 32 | 33 | * serve with hot reload at localhost:8080 34 | > npm run dev 35 | 36 | * build for production with minification 37 | > npm run build 38 | 39 | 这是在我站点上跑着的[例子](http://item.redream.cn/chat/),大家可以看一看,在手机上效果更加,最近校招比较忙,就花了两天,没考虑兼容,欢迎大家提出意见。 40 | 41 | ------- 42 | > 这是我第一次写技术介绍文章,其实我也并没有介绍什么细节。不过感觉上面提到的每一个知识点都可以讲很多。一想写起来那么多就没耐心了,看来还是太毛躁。希望大家多多包涵,我会慢慢改进的,大家一起进步! 43 | 44 | https://github.com/secreter/websocket_chat 45 | -------------------------------------------------------------------------------- /build/build.js: -------------------------------------------------------------------------------- 1 | // https://github.com/shelljs/shelljs 2 | require('shelljs/global') 3 | env.NODE_ENV = 'production' 4 | 5 | var path = require('path') 6 | var config = require('../config') 7 | var ora = require('ora') 8 | var webpack = require('webpack') 9 | var webpackConfig = require('./webpack.prod.conf') 10 | 11 | console.log( 12 | ' Tip:\n' + 13 | ' Built files are meant to be served over an HTTP server.\n' + 14 | ' Opening index.html over file:// won\'t work.\n' 15 | ) 16 | 17 | var spinner = ora('building for production...') 18 | spinner.start() 19 | 20 | var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory) 21 | rm('-rf', assetsPath) 22 | mkdir('-p', assetsPath) 23 | cp('-R', 'static/', assetsPath) 24 | 25 | webpack(webpackConfig, function (err, stats) { 26 | spinner.stop() 27 | if (err) throw err 28 | process.stdout.write(stats.toString({ 29 | colors: true, 30 | modules: false, 31 | children: false, 32 | chunks: false, 33 | chunkModules: false 34 | }) + '\n') 35 | }) 36 | -------------------------------------------------------------------------------- /build/dev-client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | require('eventsource-polyfill') 3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 4 | 5 | hotClient.subscribe(function (event) { 6 | if (event.action === 'reload') { 7 | window.location.reload() 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /build/dev-server.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var express = require('express') 3 | var webpack = require('webpack') 4 | var config = require('../config') 5 | var proxyMiddleware = require('http-proxy-middleware') 6 | var webpackConfig = process.env.NODE_ENV === 'testing' 7 | ? require('./webpack.prod.conf') 8 | : require('./webpack.dev.conf') 9 | 10 | // default port where dev server listens for incoming traffic 11 | var port = process.env.PORT || config.dev.port 12 | // Define HTTP proxies to your custom API backend 13 | // https://github.com/chimurai/http-proxy-middleware 14 | var proxyTable = config.dev.proxyTable 15 | 16 | var app = express() 17 | var compiler = webpack(webpackConfig) 18 | 19 | var devMiddleware = require('webpack-dev-middleware')(compiler, { 20 | publicPath: webpackConfig.output.publicPath, 21 | stats: { 22 | colors: true, 23 | chunks: false 24 | } 25 | }) 26 | 27 | var hotMiddleware = require('webpack-hot-middleware')(compiler) 28 | // force page reload when html-webpack-plugin template changes 29 | compiler.plugin('compilation', function (compilation) { 30 | compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { 31 | hotMiddleware.publish({ action: 'reload' }) 32 | cb() 33 | }) 34 | }) 35 | 36 | // proxy api requests 37 | Object.keys(proxyTable).forEach(function (context) { 38 | var options = proxyTable[context] 39 | if (typeof options === 'string') { 40 | options = { target: options } 41 | } 42 | app.use(proxyMiddleware(context, options)) 43 | }) 44 | 45 | // handle fallback for HTML5 history API 46 | app.use(require('connect-history-api-fallback')()) 47 | 48 | // serve webpack bundle output 49 | app.use(devMiddleware) 50 | 51 | // enable hot-reload and state-preserving 52 | // compilation error display 53 | app.use(hotMiddleware) 54 | 55 | // serve pure static assets 56 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) 57 | app.use(staticPath, express.static('./static')) 58 | 59 | module.exports = app.listen(port, function (err) { 60 | if (err) { 61 | console.log(err) 62 | return 63 | } 64 | console.log('Listening at http://localhost:' + port + '\n') 65 | }) 66 | -------------------------------------------------------------------------------- /build/utils.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 4 | 5 | exports.assetsPath = function (_path) { 6 | var assetsSubDirectory = process.env.NODE_ENV === 'production' 7 | ? config.build.assetsSubDirectory 8 | : config.dev.assetsSubDirectory 9 | return path.posix.join(assetsSubDirectory, _path) 10 | } 11 | 12 | exports.cssLoaders = function (options) { 13 | options = options || {} 14 | // generate loader string to be used with extract text plugin 15 | function generateLoaders (loaders) { 16 | var sourceLoader = loaders.map(function (loader) { 17 | var extraParamChar 18 | if (/\?/.test(loader)) { 19 | loader = loader.replace(/\?/, '-loader?') 20 | extraParamChar = '&' 21 | } else { 22 | loader = loader + '-loader' 23 | extraParamChar = '?' 24 | } 25 | return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '') 26 | }).join('!') 27 | 28 | if (options.extract) { 29 | return ExtractTextPlugin.extract('vue-style-loader', sourceLoader) 30 | } else { 31 | return ['vue-style-loader', sourceLoader].join('!') 32 | } 33 | } 34 | 35 | // http://vuejs.github.io/vue-loader/configurations/extract-css.html 36 | return { 37 | css: generateLoaders(['css']), 38 | postcss: generateLoaders(['css']), 39 | less: generateLoaders(['css', 'less']), 40 | sass: generateLoaders(['css', 'sass?indentedSyntax']), 41 | scss: generateLoaders(['css', 'sass']), 42 | stylus: generateLoaders(['css', 'stylus']), 43 | styl: generateLoaders(['css', 'stylus']) 44 | } 45 | } 46 | 47 | // Generate loaders for standalone style files (outside of .vue) 48 | exports.styleLoaders = function (options) { 49 | var output = [] 50 | var loaders = exports.cssLoaders(options) 51 | for (var extension in loaders) { 52 | var loader = loaders[extension] 53 | output.push({ 54 | test: new RegExp('\\.' + extension + '$'), 55 | loader: loader 56 | }) 57 | } 58 | return output 59 | } 60 | -------------------------------------------------------------------------------- /build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var utils = require('./utils') 4 | var projectRoot = path.resolve(__dirname, '../') 5 | 6 | module.exports = { 7 | entry: { 8 | app: './src/main.js' 9 | }, 10 | output: { 11 | path: config.build.assetsRoot, 12 | publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath, 13 | filename: '[name].js' 14 | }, 15 | resolve: { 16 | extensions: ['', '.js', '.vue'], 17 | fallback: [path.join(__dirname, '../node_modules')], 18 | alias: { 19 | 'src': path.resolve(__dirname, '../src'), 20 | 'assets': path.resolve(__dirname, '../src/assets'), 21 | 'components': path.resolve(__dirname, '../src/components') 22 | } 23 | }, 24 | resolveLoader: { 25 | fallback: [path.join(__dirname, '../node_modules')] 26 | }, 27 | module: { 28 | loaders: [ 29 | { 30 | test: /\.vue$/, 31 | loader: 'vue' 32 | }, 33 | { 34 | test: /\.js$/, 35 | loader: 'babel', 36 | include: projectRoot, 37 | exclude: /node_modules/ 38 | }, 39 | { 40 | test: /\.json$/, 41 | loader: 'json' 42 | }, 43 | { 44 | test: /\.html$/, 45 | loader: 'vue-html' 46 | }, 47 | { 48 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 49 | loader: 'url', 50 | query: { 51 | limit: 10000, 52 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 53 | } 54 | }, 55 | { 56 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 57 | loader: 'url', 58 | query: { 59 | limit: 10000, 60 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 61 | } 62 | } 63 | ] 64 | }, 65 | vue: { 66 | loaders: utils.cssLoaders() 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | var config = require('../config') 2 | var webpack = require('webpack') 3 | var merge = require('webpack-merge') 4 | var utils = require('./utils') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | var HtmlWebpackPlugin = require('html-webpack-plugin') 7 | 8 | // add hot-reload related code to entry chunks 9 | Object.keys(baseWebpackConfig.entry).forEach(function (name) { 10 | baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) 11 | }) 12 | 13 | module.exports = merge(baseWebpackConfig, { 14 | module: { 15 | loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) 16 | }, 17 | // eval-source-map is faster for development 18 | devtool: '#eval-source-map', 19 | devServer: { 20 | contentBase: "./build/",//本地服务器所加载的页面所在的目录 21 | hot: true, 22 | colors: true,//终端中输出结果为彩色 23 | historyApiFallback: true,//不跳转 24 | inline: true//实时刷新 25 | }, 26 | plugins: [ 27 | new webpack.DefinePlugin({ 28 | 'process.env': config.dev.env 29 | }), 30 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage 31 | new webpack.optimize.OccurenceOrderPlugin(), 32 | new webpack.HotModuleReplacementPlugin(), 33 | new webpack.NoErrorsPlugin(), 34 | // https://github.com/ampedandwired/html-webpack-plugin 35 | new HtmlWebpackPlugin({ 36 | filename: 'index.html', 37 | template: 'index.html', 38 | inject: true 39 | }) 40 | ] 41 | }) 42 | -------------------------------------------------------------------------------- /build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var utils = require('./utils') 4 | var webpack = require('webpack') 5 | var merge = require('webpack-merge') 6 | var baseWebpackConfig = require('./webpack.base.conf') 7 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 8 | var HtmlWebpackPlugin = require('html-webpack-plugin') 9 | var env = process.env.NODE_ENV === 'testing' 10 | ? require('../config/test.env') 11 | : config.build.env 12 | 13 | var webpackConfig = merge(baseWebpackConfig, { 14 | module: { 15 | loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) 16 | }, 17 | devtool: config.build.productionSourceMap ? '#source-map' : false, 18 | output: { 19 | path: config.build.assetsRoot, 20 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 21 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 22 | }, 23 | vue: { 24 | loaders: utils.cssLoaders({ 25 | sourceMap: config.build.productionSourceMap, 26 | extract: true 27 | }) 28 | }, 29 | plugins: [ 30 | // http://vuejs.github.io/vue-loader/workflow/production.html 31 | new webpack.DefinePlugin({ 32 | 'process.env': env 33 | }), 34 | new webpack.optimize.UglifyJsPlugin({ 35 | compress: { 36 | warnings: false 37 | } 38 | }), 39 | new webpack.optimize.OccurenceOrderPlugin(), 40 | // extract css into its own file 41 | new ExtractTextPlugin('./[name].[contenthash].css'), 42 | // generate dist index.html with correct asset hash for caching. 43 | // you can customize output by editing /index.html 44 | // see https://github.com/ampedandwired/html-webpack-plugin 45 | new HtmlWebpackPlugin({ 46 | filename: process.env.NODE_ENV === 'testing' 47 | ? 'index.html' 48 | : config.build.index, 49 | template: 'index.html', 50 | inject: true, 51 | minify: { 52 | removeComments: true, 53 | collapseWhitespace: true, 54 | removeAttributeQuotes: true 55 | // more options: 56 | // https://github.com/kangax/html-minifier#options-quick-reference 57 | }, 58 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 59 | chunksSortMode: 'dependency' 60 | }), 61 | // split vendor js into its own file 62 | new webpack.optimize.CommonsChunkPlugin({ 63 | name: 'vendor', 64 | minChunks: function (module, count) { 65 | // any required modules inside node_modules are extracted to vendor 66 | return ( 67 | module.resource && 68 | /\.js$/.test(module.resource) && 69 | module.resource.indexOf( 70 | path.join(__dirname, '../node_modules') 71 | ) === 0 72 | ) 73 | } 74 | }), 75 | // extract webpack runtime and module manifest to its own file in order to 76 | // prevent vendor hash from being updated whenever app bundle is updated 77 | new webpack.optimize.CommonsChunkPlugin({ 78 | name: 'manifest', 79 | chunks: ['vendor'] 80 | }) 81 | ] 82 | }) 83 | 84 | if (config.build.productionGzip) { 85 | var CompressionWebpackPlugin = require('compression-webpack-plugin') 86 | 87 | webpackConfig.plugins.push( 88 | new CompressionWebpackPlugin({ 89 | asset: '[path].gz[query]', 90 | algorithm: 'gzip', 91 | test: new RegExp( 92 | '\\.(' + 93 | config.build.productionGzipExtensions.join('|') + 94 | ')$' 95 | ), 96 | threshold: 10240, 97 | minRatio: 0.8 98 | }) 99 | ) 100 | } 101 | 102 | module.exports = webpackConfig 103 | -------------------------------------------------------------------------------- /config/dev.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var prodEnv = require('./prod.env') 3 | 4 | module.exports = merge(prodEnv, { 5 | NODE_ENV: '"development"' 6 | }) 7 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | // see http://vuejs-templates.github.io/webpack for documentation. 2 | var path = require('path') 3 | 4 | module.exports = { 5 | build: { 6 | env: require('./prod.env'), 7 | index: path.resolve(__dirname, '../dist/index.html'), 8 | assetsRoot: path.resolve(__dirname, '../dist'), 9 | assetsSubDirectory: 'static', 10 | assetsPublicPath: './', 11 | productionSourceMap: true, 12 | // Gzip off by default as many popular static hosts such as 13 | // Surge or Netlify already gzip all static assets for you. 14 | // Before setting to `true`, make sure to: 15 | // npm install --save-dev compression-webpack-plugin 16 | productionGzip: false, 17 | productionGzipExtensions: ['js', 'css'] 18 | }, 19 | dev: { 20 | env: require('./dev.env'), 21 | port: 8080, 22 | assetsSubDirectory: 'static', 23 | assetsPublicPath: '/', 24 | proxyTable: {}, 25 | // CSS Sourcemaps off by default because relative paths are "buggy" 26 | // with this option, according to the CSS-Loader README 27 | // (https://github.com/webpack/css-loader#sourcemaps) 28 | // In our experience, they generally work as expected, 29 | // just be aware of this issue when enabling this option. 30 | cssSourceMap: false 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /config/prod.env.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NODE_ENV: '"production"' 3 | } 4 | -------------------------------------------------------------------------------- /config/test.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var devEnv = require('./dev.env') 3 | 4 | module.exports = merge(devEnv, { 5 | NODE_ENV: '"testing"' 6 | }) 7 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 江湖聊天室——陌生人你好 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chat", 3 | "version": "1.0.0", 4 | "description": "online chat for redream ", 5 | "author": "So <1979510177@qq.com>", 6 | "private": true, 7 | "scripts": { 8 | "start": "webpack-dev-server --progress --inline --hot", 9 | "dev": "node build/dev-server.js", 10 | "build": "node build/build.js", 11 | "unit": "karma start test/unit/karma.conf.js --single-run", 12 | "test": "npm run unit" 13 | }, 14 | "dependencies": { 15 | "babel-runtime": "^6.0.0", 16 | "less": "^2.7.1", 17 | "less-loader": "^2.2.3", 18 | "socket.io": "^1.4.8", 19 | "vue": "^1.0.21", 20 | "vue-router": "^0.7.13" 21 | }, 22 | "devDependencies": { 23 | "babel-core": "^6.0.0", 24 | "babel-loader": "^6.0.0", 25 | "babel-plugin-transform-runtime": "^6.0.0", 26 | "babel-preset-es2015": "^6.0.0", 27 | "babel-preset-stage-2": "^6.0.0", 28 | "babel-register": "^6.0.0", 29 | "chai": "^3.5.0", 30 | "connect-history-api-fallback": "^1.1.0", 31 | "css-loader": "^0.23.0", 32 | "eventsource-polyfill": "^0.9.6", 33 | "express": "^4.13.3", 34 | "extract-text-webpack-plugin": "^1.0.1", 35 | "file-loader": "^0.8.4", 36 | "function-bind": "^1.0.2", 37 | "html-webpack-plugin": "^2.8.1", 38 | "http-proxy-middleware": "^0.12.0", 39 | "inject-loader": "^2.0.1", 40 | "isparta-loader": "^2.0.0", 41 | "json-loader": "^0.5.4", 42 | "karma": "^0.13.15", 43 | "karma-coverage": "^0.5.5", 44 | "karma-mocha": "^0.2.2", 45 | "karma-phantomjs-launcher": "^1.0.0", 46 | "karma-sinon-chai": "^1.2.0", 47 | "karma-sourcemap-loader": "^0.3.7", 48 | "karma-spec-reporter": "0.0.24", 49 | "karma-webpack": "^1.7.0", 50 | "less-loader": "^2.2.3", 51 | "lolex": "^1.4.0", 52 | "mocha": "^2.4.5", 53 | "ora": "^0.2.0", 54 | "phantomjs-prebuilt": "^2.1.3", 55 | "shelljs": "^0.6.0", 56 | "sinon": "^1.17.3", 57 | "sinon-chai": "^2.8.0", 58 | "url-loader": "^0.5.7", 59 | "vue-hot-reload-api": "^1.2.0", 60 | "vue-html-loader": "^1.0.0", 61 | "vue-loader": "^8.3.0", 62 | "vue-style-loader": "^1.0.0", 63 | "webpack": "^1.13.2", 64 | "webpack-dev-middleware": "^1.4.0", 65 | "webpack-dev-server": "^1.15.1", 66 | "webpack-hot-middleware": "^2.6.0", 67 | "webpack-merge": "^0.8.3" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | // var fs = require("fs"); 2 | // var options = { 3 | // key: fs.readFileSync('./2_node.redream.cn.key'), 4 | // cert: fs.readFileSync('./1_node.redream.cn_cert.crt') 5 | // }; 6 | var app = require('express')(); 7 | // var https = require('https').Server(options,app); 8 | var http = require('http').Server(app); 9 | var io = require('socket.io')(http); 10 | 11 | app.get('/', function(req, res){ 12 | res.send('

Welcome Realtime Server

'); 13 | }); 14 | 15 | //在线用户 16 | var onlineUsers = {}; 17 | //当前在线人数 18 | var onlineCount = 0; 19 | 20 | io.on('connection', function(socket){ 21 | console.log('a user connected'); 22 | 23 | //监听新用户加入 24 | socket.on('login', function(obj){ 25 | //将新加入用户的唯一标识当作socket的名称,后面退出的时候会用到 26 | socket.name = obj.userid; 27 | 28 | //检查在线列表,如果不在里面就加入 29 | if(!onlineUsers.hasOwnProperty(obj.userid)) { 30 | onlineUsers[obj.userid] = obj; 31 | //在线人数+1 32 | onlineCount++; 33 | } 34 | 35 | //向所有客户端广播用户加入 36 | io.emit('login', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj,login:true}); 37 | console.log(obj.username+'加入了聊天室'); 38 | }); 39 | 40 | //监听用户退出 41 | socket.on('disconnect', function(){ 42 | //将退出的用户从在线列表中删除 43 | if(onlineUsers.hasOwnProperty(socket.name)) { 44 | //退出用户的信息 45 | var obj = {userid:socket.name, username:onlineUsers[socket.name]}; 46 | 47 | //删除 48 | delete onlineUsers[socket.name]; 49 | //在线人数-1 50 | onlineCount--; 51 | 52 | //向所有客户端广播用户退出 53 | io.emit('logout', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj,logout:true}); 54 | console.log(obj.username+'退出了聊天室'); 55 | } 56 | }); 57 | 58 | //监听用户发布聊天内容 59 | socket.on('changeInfo', function(obj){ 60 | //向所有客户端广播发布的消息 61 | io.emit('changeInfo', obj); 62 | console.log(obj.username+'更改了信息'); 63 | }); 64 | //监听更改信息 65 | socket.on('message', function(obj){ 66 | //向所有客户端广播发布的消息 67 | io.emit('message', obj); 68 | console.log(obj.username+'说:'+obj.msg); 69 | }); 70 | 71 | }); 72 | 73 | http.listen(3000, function(){ 74 | console.log('listening on *:3000'); 75 | }); 76 | // https.createServer(options).listen(3000, function () { 77 | // console.log('Https server listening on port ' + 3000); 78 | // }); 79 | // https.createServer(options,function(req,res){ 80 | // res.writeHead(200); 81 | // res.end('hello world\n'); 82 | // }).listen(3000,'127.0.0.1'); -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "realtime-server", 3 | "version": "0.0.1", 4 | "description": "my first realtime server", 5 | "dependencies": { 6 | "express": "^4.14.0", 7 | "socket.io": "^1.4.8" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 25 | 26 | 46 | -------------------------------------------------------------------------------- /src/api/client.js: -------------------------------------------------------------------------------- 1 | import io from 'socket.io-client' 2 | const CHAT={ 3 | msgObj:document.getElementsByClassName("body-wrapper")[0], 4 | username:null, 5 | userid:null, 6 | color:null, 7 | socket:null, 8 | onlineCount:0, 9 | onlineUsers:null, 10 | msgArr:[], 11 | //让浏览器滚动条保持在最低部 12 | scrollToBottom:function(){ 13 | // window.scrollTo(0, 900000); 14 | }, 15 | //退出,本例只是一个简单的刷新 16 | logout:function(){ 17 | this.socket.disconnect(); 18 | // location.reload(); 19 | }, 20 | //提交聊天消息内容 21 | submit:function(msg){ 22 | if(msg != ''){ 23 | let obj = { 24 | userid: this.userid, 25 | username: this.username, 26 | msg: msg, 27 | color: this.color 28 | }; 29 | this.socket.emit('message', obj); 30 | }else{ 31 | console.log('msg is null') 32 | } 33 | 34 | return false; 35 | }, 36 | genUid:function(){ 37 | return new Date().getTime()+""+Math.floor(Math.random()*899+100); 38 | }, 39 | //更新系统消息,本例中在用户加入、退出的时候调用 40 | updateSysMsg:function(o, action){ 41 | //当前在线用户列表 42 | this.onlineUsers=o.onlineUsers; 43 | //当前在线人数 44 | this.onlineCount = o.onlineCount; 45 | //新加入用户的信息 46 | var user = o.user; 47 | 48 | //更新在线人数 49 | var userhtml = ''; 50 | var separator = ''; 51 | // for(key in onlineUsers) { 52 | // if(onlineUsers.hasOwnProperty(key)){ 53 | // userhtml += separator+onlineUsers[key]; 54 | // separator = '、'; 55 | // } 56 | // } 57 | // d.getElementById("onlinecount").innerHTML = '当前共有 '+onlineCount+' 人在线,在线列表:'+userhtml; 58 | 59 | // //添加系统消息 60 | // var html = ''; 61 | // html += '
'; 62 | // html += user.username; 63 | // html += (action == 'login') ? ' 加入了聊天室' : ' 退出了聊天室'; 64 | // html += '
'; 65 | // var section = d.createElement('section'); 66 | // section.className = 'system J-mjrlinkWrap J-cutMsg'; 67 | // section.innerHTML = html; 68 | // this.msgObj.appendChild(section); 69 | // this.scrollToBottom(); 70 | }, 71 | changeInfo(){ 72 | this.userid = localStorage.getItem('userid'); 73 | this.username = localStorage.getItem('name'); 74 | this.color = localStorage.getItem('color'); 75 | this.weichat = localStorage.getItem('weichat'); 76 | this.socket.emit('changeInfo', {userid:this.userid, username:this.username,color:this.color,weichat:this.weichat}); 77 | }, 78 | init:function(){ 79 | /* 80 | 客户端根据时间和随机数生成uid,这样使得聊天室用户名称可以重复。 81 | 实际项目中,如果是需要用户登录,那么直接采用用户的uid来做标识就可以 82 | */ 83 | // this.userid = this.genUid(); 84 | this.userid = localStorage.getItem('userid'); 85 | this.username = localStorage.getItem('name'); 86 | this.color = localStorage.getItem('color'); 87 | this.weichat = localStorage.getItem('weichat'); 88 | 89 | if (!this.userid) {return} 90 | // this.username = Math.floor(Math.random()*10); 91 | 92 | //连接websocket后端服务器 93 | this.socket = io.connect('wss://node.redream.cn'); 94 | 95 | //告诉服务器端有用户登录 96 | this.socket.emit('login', {userid:this.userid, username:this.username,color:this.color,weichat:this.weichat}); 97 | //心跳包,30s左右无数据浏览器会断开连接Heartbeat 98 | 99 | setInterval(() => { 100 | this.socket.emit('heartbeat', 1); 101 | },10000) 102 | //监听新用户登录 103 | this.socket.on('login', function(obj){ 104 | CHAT.updateSysMsg(obj, 'logout'); 105 | CHAT.msgArr.push(obj) 106 | }); 107 | 108 | this.socket.on('changeInfo', function(o){ 109 | CHAT.onlineUsers[o.userid]=o 110 | console.log(o) 111 | }); 112 | //监听用户退出 113 | this.socket.on('logout', function(o){ 114 | CHAT.updateSysMsg(o, 'logout'); 115 | }); 116 | 117 | //监听消息发送 118 | this.socket.on('message', function(obj){ 119 | // var isme = (obj.userid == CHAT.userid) ? true : false; 120 | CHAT.msgArr.push(obj) 121 | }); 122 | 123 | } 124 | } 125 | export default CHAT -------------------------------------------------------------------------------- /src/assets/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secreter/websocket_chat/11778a19aabbfa1fa04def9640a1a231c602c987/src/assets/1.jpg -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secreter/websocket_chat/11778a19aabbfa1fa04def9640a1a231c602c987/src/assets/logo.png -------------------------------------------------------------------------------- /src/components/ChatBody.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/components/ChatFoot.vue: -------------------------------------------------------------------------------- 1 | 7 | 8 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/components/ChatHead.vue: -------------------------------------------------------------------------------- 1 | 20 | 21 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/components/GroupInfo.vue: -------------------------------------------------------------------------------- 1 | 7 | 25 | -------------------------------------------------------------------------------- /src/components/GroupInfoBody.vue: -------------------------------------------------------------------------------- 1 | 74 | 148 | -------------------------------------------------------------------------------- /src/components/GroupInfoHead.vue: -------------------------------------------------------------------------------- 1 | 17 | 43 | -------------------------------------------------------------------------------- /src/components/OtherMsg.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 25 | -------------------------------------------------------------------------------- /src/components/SelfMsg.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 25 | -------------------------------------------------------------------------------- /src/components/SystemMsg.vue: -------------------------------------------------------------------------------- 1 | 8 | 17 | -------------------------------------------------------------------------------- /src/components/login.vue: -------------------------------------------------------------------------------- 1 | 29 | 30 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/components/util/dialog.vue: -------------------------------------------------------------------------------- 1 | 8 | 34 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | import routerMap from './router/index' 4 | import App from './App' 5 | 6 | Vue.use(VueRouter) 7 | let router = new VueRouter() 8 | routerMap(router) 9 | /* eslint-disable no-new */ 10 | let vm={ 11 | components: { App } 12 | } 13 | 14 | router.start(vm, 'body') -------------------------------------------------------------------------------- /src/router/index.js: -------------------------------------------------------------------------------- 1 | import GroupInfo from '../components/GroupInfo' 2 | import Login from '../components/login' 3 | export default function (router) { 4 | router.map({ 5 | /** 6 | * @param {String} from '/store/ab' or '/store/side' 7 | */ 8 | '/groupinfo': { 9 | name: 'groupinfo', 10 | component: GroupInfo 11 | }, 12 | '/login': { 13 | name: 'login', 14 | component: Login 15 | } 16 | }) 17 | } -------------------------------------------------------------------------------- /src/util/index.js: -------------------------------------------------------------------------------- 1 | export function randomColor(){ 2 | return "#"+(~~(Math.random()*(1<<24))).toString(16) 3 | } 4 | export function genUid(){ 5 | return new Date().getTime()+""+Math.floor(Math.random()*899+100); 6 | } -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secreter/websocket_chat/11778a19aabbfa1fa04def9640a1a231c602c987/static/.gitkeep -------------------------------------------------------------------------------- /test/unit/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "globals": { 6 | "expect": true, 7 | "sinon": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/unit/index.js: -------------------------------------------------------------------------------- 1 | // Polyfill fn.bind() for PhantomJS 2 | /* eslint-disable no-extend-native */ 3 | Function.prototype.bind = require('function-bind') 4 | 5 | // require all test files (files that ends with .spec.js) 6 | var testsContext = require.context('./specs', true, /\.spec$/) 7 | testsContext.keys().forEach(testsContext) 8 | 9 | // require all src files except main.js for coverage. 10 | // you can also change this to match only the subset of files that 11 | // you want coverage for. 12 | var srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/) 13 | srcContext.keys().forEach(srcContext) 14 | -------------------------------------------------------------------------------- /test/unit/karma.conf.js: -------------------------------------------------------------------------------- 1 | // This is a karma config file. For more details see 2 | // http://karma-runner.github.io/0.13/config/configuration-file.html 3 | // we are also using it with karma-webpack 4 | // https://github.com/webpack/karma-webpack 5 | 6 | var path = require('path') 7 | var merge = require('webpack-merge') 8 | var baseConfig = require('../../build/webpack.base.conf') 9 | var utils = require('../../build/utils') 10 | var webpack = require('webpack') 11 | var projectRoot = path.resolve(__dirname, '../../') 12 | 13 | var webpackConfig = merge(baseConfig, { 14 | // use inline sourcemap for karma-sourcemap-loader 15 | module: { 16 | loaders: utils.styleLoaders() 17 | }, 18 | devtool: '#inline-source-map', 19 | vue: { 20 | loaders: { 21 | js: 'isparta' 22 | } 23 | }, 24 | plugins: [ 25 | new webpack.DefinePlugin({ 26 | 'process.env': require('../../config/test.env') 27 | }) 28 | ] 29 | }) 30 | 31 | // no need for app entry during tests 32 | delete webpackConfig.entry 33 | 34 | // make sure isparta loader is applied before eslint 35 | webpackConfig.module.preLoaders = webpackConfig.module.preLoaders || [] 36 | webpackConfig.module.preLoaders.unshift({ 37 | test: /\.js$/, 38 | loader: 'isparta', 39 | include: path.resolve(projectRoot, 'src') 40 | }) 41 | 42 | // only apply babel for test files when using isparta 43 | webpackConfig.module.loaders.some(function (loader, i) { 44 | if (loader.loader === 'babel') { 45 | loader.include = path.resolve(projectRoot, 'test/unit') 46 | return true 47 | } 48 | }) 49 | 50 | module.exports = function (config) { 51 | config.set({ 52 | // to run in additional browsers: 53 | // 1. install corresponding karma launcher 54 | // http://karma-runner.github.io/0.13/config/browsers.html 55 | // 2. add it to the `browsers` array below. 56 | browsers: ['PhantomJS'], 57 | frameworks: ['mocha', 'sinon-chai'], 58 | reporters: ['spec', 'coverage'], 59 | files: ['./index.js'], 60 | preprocessors: { 61 | './index.js': ['webpack', 'sourcemap'] 62 | }, 63 | webpack: webpackConfig, 64 | webpackMiddleware: { 65 | noInfo: true 66 | }, 67 | coverageReporter: { 68 | dir: './coverage', 69 | reporters: [ 70 | { type: 'lcov', subdir: '.' }, 71 | { type: 'text-summary' } 72 | ] 73 | } 74 | }) 75 | } 76 | -------------------------------------------------------------------------------- /test/unit/specs/Hello.spec.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Hello from 'src/components/Hello' 3 | 4 | describe('Hello.vue', () => { 5 | it('should render correct contents', () => { 6 | const vm = new Vue({ 7 | template: '
', 8 | components: { Hello } 9 | }).$mount() 10 | expect(vm.$el.querySelector('.hello h1').textContent).to.contain('Hello World!') 11 | }) 12 | }) 13 | --------------------------------------------------------------------------------