├── .babelrc
├── .editorconfig
├── .gitignore
├── .postcssrc.js
├── 2.md
├── 3.md
├── 4.md
├── 5.md
├── 6.md
├── README.md
├── build
├── build.js
├── check-versions.js
├── utils.js
├── vue-loader.conf.js
├── webpack.base.conf.js
├── webpack.dev.conf.js
└── webpack.prod.conf.js
├── config
├── dev.env.js
├── index.js
└── prod.env.js
├── index.html
├── package.json
├── server
└── index.js
├── src
├── App.vue
├── app.styl
├── assets
│ ├── close.svg
│ ├── logo.png
│ ├── success.svg
│ └── warn.svg
├── components
│ ├── dialog
│ │ ├── index.styl
│ │ └── index.vue
│ └── message
│ │ └── index.js
├── main.js
└── router
│ └── index.js
└── static
└── .gitkeep
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["env", {
4 | "modules": false,
5 | "targets": {
6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
7 | }
8 | }],
9 | "stage-2"
10 | ],
11 | "plugins": ["transform-vue-jsx", "transform-runtime"]
12 | }
13 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules/
3 | /dist/
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Editor directories and files
9 | .idea
10 | .vscode
11 | *.suo
12 | *.ntvs*
13 | *.njsproj
14 | *.sln
15 |
--------------------------------------------------------------------------------
/.postcssrc.js:
--------------------------------------------------------------------------------
1 | // https://github.com/michael-ciniawsky/postcss-load-config
2 |
3 | module.exports = {
4 | "plugins": {
5 | "postcss-import": {},
6 | "postcss-url": {},
7 | // to edit target browsers: use "browserslist" field in package.json
8 | "autoprefixer": {}
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/2.md:
--------------------------------------------------------------------------------
1 | # Nodejs + WebSocket + Vue 实现多人聊天室WebIM功能 - 第二章
2 |
3 | ## 前言
4 | 在[《Nodejs + WebSocket简单介绍及示例 - 第一章》](https://www.toutiao.com/i6683747519056314892/)中简单的介绍了,Nodejs + WebSocket的使用方法及作用,今天就用它来搭建一个简单的聊天室功能。
5 |
6 | 
7 |
8 | 1、Nodejs+WebSocket创建后台服务器功能
9 | 2、Vue视图层,接收后台数据并渲染页面
10 | 3、LocalStorage存储会话ID等用户信息
11 |
12 | ## vue + webpack 生成vue项目
13 | 脚手架搭建项目也是非常好用,简单命令即可搞定
14 | ```bash
15 | # vue init webpack web-im
16 | ```
17 | 然后一路向下,填写项目名称,描述,作者等等信息,完成安装。
18 |
19 | 现在都可以自动安装模块了,当然,你可以可以到目录下面执行`npm install`
20 |
21 | ```bash
22 | # cd web-im
23 | # npm install
24 | ```
25 |
26 | 
27 |
28 | 这就是整个生成后的项目结构。
29 |
30 |
31 | ## WebSocket服务端
32 | 在项目根目录下新建server/index.js文件。
33 | ```javascript
34 | var ws = require("nodejs-websocket");
35 | // 这里用到了moment,请大家自行安装
36 | var moment = require('moment');
37 |
38 | console.log("开始建立连接...")
39 |
40 | let users = [];
41 |
42 | // 向所有连接的客户端广播
43 | function boardcast(obj) {
44 | server.connections.forEach(function(conn) {
45 | conn.sendText(JSON.stringify(obj));
46 | })
47 | }
48 |
49 | function getDate(){
50 | return moment().format('YYYY-MM-DD HH:mm:ss')
51 | }
52 |
53 | var server = ws.createServer(function(conn){
54 | conn.on("text", function (obj) {
55 | obj = JSON.parse(obj);
56 | if(obj.type===1){
57 | users.push({
58 | nickname: obj.nickname,
59 | uid: obj.uid
60 | });
61 | boardcast({
62 | type: 1,
63 | date: getDate(),
64 | msg: obj.nickname+'加入聊天室',
65 | users: users,
66 | uid: obj.uid,
67 | nickname: obj.nickname
68 | });
69 | } else {
70 | boardcast({
71 | type: 2,
72 | date: getDate(),
73 | msg: obj.msg,
74 | uid: obj.uid,
75 | nickname: obj.nickname
76 | });
77 | }
78 | })
79 | conn.on("close", function (code, reason) {
80 | console.log("关闭连接")
81 | });
82 | conn.on("error", function (code, reason) {
83 | console.log("异常关闭")
84 | });
85 | }).listen(8001)
86 | console.log("WebSocket建立完毕")
87 | ```
88 |
89 | 这里和[《Nodejs + WebSocket简单介绍及示例 - 第一章》](https://www.toutiao.com/i6683747519056314892/)大体结构相同,不同的是,这里向客户端发送消息是用的一个方法
90 | ```javascript
91 | server.connections.forEach(function(conn) {
92 | conn.sendText(JSON.stringify(obj));
93 | })
94 | ```
95 |
96 | 遍历所有连接,发送信息。
97 |
98 |
99 | 这里为什么要`JSON.stringify(obj)`转换成字符串???
100 |
101 |
102 | 那是`sendText`方法只能传入字符串,所以我们需要将我们的对象转换一下。
103 |
104 | 同时,大家应该可以看出,在`conn.on("text", ()=>{})`的时候判断了一个从客户端传入的type,这个操作是判断用户是否是第一次进入。
105 |
106 |
107 | ## WebSocket客户端视图层
108 | ```html
109 |
110 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 | {{item.msg}}
125 |
126 |
127 | {{item.nickname}}
128 | {{item.msg}}
129 |
130 |
131 |
132 |
136 |
137 |
138 | ```
139 |
140 | 
141 |
142 |
143 | 样式方面就不做解释了,都是非常简单的样式,有兴趣的可以点击最下方获取源码查看。
144 |
145 | ## WebSocket客户端
146 | ```javascript
147 | export default {
148 | ...
149 | data(){
150 | return {
151 | uid: '',
152 | nickname: '',
153 | socket: '',
154 | msg: '',
155 | messageList: []
156 | }
157 | },
158 | mounted() {
159 | let vm = this;
160 | let user = localStorage.getItem('WEB_IM_USER');
161 | user = user && JSON.parse(user) || {};
162 | vm.uid = user.uid;
163 | vm.nickname = user.nickname;
164 |
165 | if(!vm.uid){
166 | vm.$refs.loginDialog.show()
167 | } else {
168 | vm.conWebSocket();
169 | }
170 | document.onkeydown = function (event) {
171 | var e = event || window.event;
172 | if (e && e.keyCode == 13) { //回车键的键值为13
173 | vm.send()
174 | }
175 | }
176 | },
177 | methods: {
178 | send(){
179 | if(!this.msg){
180 | return
181 | }
182 | this.sendMessage(2, this.msg)
183 | },
184 | sendMessage(type, msg){
185 | this.socket.send(JSON.stringify({
186 | uid: this.uid,
187 | type: type,
188 | nickname: this.nickname,
189 | msg: msg
190 | }));
191 | this.msg = '';
192 | },
193 | conWebSocket(){
194 | let vm = this;
195 | if(window.WebSocket){
196 | vm.socket = new WebSocket('ws://localhost:8001');
197 | let socket = vm.socket;
198 |
199 | socket.onopen = function(e){
200 | console.log("连接服务器成功");
201 | if(!vm.uid){
202 | // 生成新的用户id,并存入localStorage
203 | vm.uid = 'web_im_' + moment().valueOf();
204 | localStorage.setItem('WEB_IM_USER', JSON.stringify({
205 | uid: vm.uid,
206 | nickname: vm.nickname
207 | }))
208 | vm.sendMessage(1)
209 | }
210 | }
211 | socket.onclose = function(e){
212 | console.log("服务器关闭");
213 | }
214 | socket.onerror = function(){
215 | console.log("连接出错");
216 | }
217 | // 接收服务器的消息
218 | socket.onmessage = function(e){
219 | let message = JSON.parse(e.data);
220 | vm.messageList.push(message);
221 | }
222 | }
223 | },
224 | login(){
225 | this.$refs.loginDialog.hide()
226 | this.conWebSocket();
227 | }
228 | }
229 | }
230 | ```
231 |
232 | 页面渲染完成后,我们`localStorage.getItem('WEB_IM_USER')`获取本地存储是否有用户信息
233 | 1、没有用户信息,弹框填写昵称,确认开始连接,并生成一个时间戳的用户id,存入localStorage
234 | 2、有用户信息,直接连接
235 | 3、`socket.onmessage`监听服务器发送过来的消息,转换成json,push到`messageList`数组中,然后渲染到页面
236 | 4、通过`type`判断是新加入用户,还是正常发送消息,显示到页面
237 | 5、通过uid,判断是否是本人发送的消息,如果是消息内容靠右显示,其他用户发送的消息都靠左显示,并设置不同背景色
238 |
239 | 这样我们就完成了一个简单的node + websocket群聊功能,你从中学习到了什么了???
240 |
241 | 最后来一睹风采
242 | 
243 |
244 | 
245 |
246 | 
247 |
248 | ## 总结
249 | Nodejs + WebSocket群聊功能和核心不知道大家有没有get到了???
250 | 其实核心代码就是它:
251 | ```javascript
252 | function boardcast(obj) {
253 | server.connections.forEach(function(conn) {
254 | conn.sendText(JSON.stringify(obj));
255 | })
256 | }
257 | ```
258 |
259 | 向所有连接者发送消息,这样所有连接者都能接收到消息。
260 |
261 |
262 | 源码地址:[源码地址](https://github.com/javanf/web-im)
263 |
264 |
--------------------------------------------------------------------------------
/3.md:
--------------------------------------------------------------------------------
1 | > Nodejs + WebSocket + Vue 一对一、一对多聊天室 - 第三章
2 |
3 |
4 | ## 前言
5 |
6 | 
7 |
8 | 如果你看到这篇文章,还没有了解前面2篇文章的同学,可以先去了解一波,这样上手更快。
9 | 推荐文章:
10 |
11 | [《Nodejs + WebSocket简单介绍及示例 - 第一章》](https://www.toutiao.com/i6683747519056314892/)
12 | [《Nodejs + WebSocket + Vue 实现多人聊天室WebIM功能 - 第二章》](https://www.toutiao.com/i6685131748478550535/)
13 |
14 |
15 | 这篇文章都是前面文章的加强版,功能升级。给大家提供一个循序渐进的学习过程,一步一步的来。
16 |
17 | 在第二篇文章结束时,我们就已经可以一对多的聊天了,就是多人群聊。这次,我们进行扩展来实现一对一、一对多功能。
18 |
19 | ## WebSocket客户端UI界面更改
20 | 有了一对一,一对多,我们就需要对直接的界面做出调整了。左边显示聊天人员列表,右边是具体消息列表。
21 |
22 | 
23 |
24 | ```html
25 |
26 |
27 |
28 |
群1
29 |
{{item.nickname}}
30 |
31 |
32 |
33 |
34 |
35 |
36 | {{item.msg}}
37 |
38 |
39 | {{item.nickname}}
40 | {{item.msg}}
41 |
42 |
43 |
44 |
48 |
49 |
50 |
51 | ...
52 | ```
53 |
54 | 这里我们就写死了一个群,叫群1,默认是所用用户进去群聊。
55 |
56 | ## WebSocket服务端
57 | ```javascript
58 | var ws = require("nodejs-websocket");
59 | var moment = require('moment');
60 |
61 | console.log("开始建立连接...")
62 |
63 | let users = [];
64 | let conns = {};
65 |
66 | function boardcast(obj) {
67 | // bridge用来实现一对一的主要参数
68 | if(obj.bridge && obj.bridge.length){
69 | obj.bridge.forEach(item=>{
70 | conns[item].sendText(JSON.stringify(obj));
71 | })
72 | return;
73 | }
74 | server.connections.forEach((conn, index) => {
75 | conn.sendText(JSON.stringify(obj));
76 | })
77 | }
78 |
79 | var server = ws.createServer(function(conn){
80 | conn.on("text", function (obj) {
81 | obj = JSON.parse(obj);
82 | // 将所有uid对应的连接conn存到一个对象里面
83 | conns[''+obj.uid+''] = conn;
84 | if(obj.type===1){
85 | let isuser = users.some(item=>{
86 | return item.uid === obj.uid
87 | })
88 | if(!isuser){
89 | users.push({
90 | nickname: obj.nickname,
91 | uid: obj.uid
92 | });
93 | }
94 | boardcast({
95 | type: 1,
96 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
97 | msg: obj.nickname+'加入聊天室',
98 | users: users,
99 | uid: obj.uid,
100 | nickname: obj.nickname,
101 | // 增加参数
102 | bridge: obj.bridge
103 | });
104 | } else {
105 | boardcast({
106 | type: 2,
107 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
108 | msg: obj.msg,
109 | uid: obj.uid,
110 | nickname: obj.nickname,
111 | // 增加参数
112 | bridge: obj.bridge
113 | });
114 | }
115 | })
116 | conn.on("close", function (code, reason) {
117 | console.log("关闭连接")
118 | });
119 | conn.on("error", function (code, reason) {
120 | console.log("异常关闭")
121 | });
122 | }).listen(8001)
123 | console.log("WebSocket建立完毕")
124 | ```
125 |
126 | > 如果上方代码阅读体验太差,可以看下方图或者直接到文章最下方,点击了解更多阅读:
127 |
128 | 
129 |
130 |
131 | 
132 |
133 | 主体结构还是和第二章类型,不同的是:
134 | 1、每次将uid对应的conn存储到一个对象conns上
135 | 2、根据客户端传入的参数bridge来判断,是群发还是一对一发送
136 | 3、群发还是第二章逻辑即可
137 | ```javascript
138 | server.connections.forEach((conn, index) => {
139 | conn.sendText(JSON.stringify(obj));
140 | })
141 | ```
142 | 4、一对一发送,bridge里面是一对一的两个用户uid,这样就可以在conns对象上找到uid对应的连接conn,并用conn发送信息即可
143 | ```javascript
144 | if(obj.bridge && obj.bridge.length){
145 | obj.bridge.forEach(item=>{
146 | conns[item].sendText(JSON.stringify(obj));
147 | })
148 | return;
149 | }
150 | ```
151 |
152 | ## WebSocket客户端
153 | ```javascript
154 | export default {
155 | ...
156 | data(){
157 | return {
158 | title: '群聊',
159 | uid: '',
160 | nickname: '',
161 | socket: '',
162 | msg: '',
163 | // 当前用户所有消息
164 | messageList: [],
165 | users: [],
166 | bridge: []
167 | }
168 | },
169 | mounted() {
170 | ...
171 | },
172 | computed: {
173 | // 当前对话渲染的msg列表
174 | currentMessage() {
175 | let vm = this;
176 | // 筛选只有bridge相同的对话,展示出来
177 | // 数组比较,先转成字符串
178 | let data = vm.messageList.filter(item=>{
179 | return item.bridge.sort().join(',') == vm.bridge.sort().join(',')
180 | })
181 | return data;
182 | }
183 | },
184 | methods: {
185 | // 切换到群聊
186 | triggerGroup() {
187 | this.bridge = [];
188 | this.title = '群聊';
189 | },
190 | // 切到具体个人
191 | triggerPersonal(item) {
192 | if(this.uid === item.uid){
193 | return;
194 | }
195 | // 将当前用户uid,和需要对话的uid放入bridge
196 | this.bridge = [this.uid, item.uid];
197 | this.title = '和' + item.nickname + '聊天';
198 | },
199 | send(){
200 | if(!this.msg){
201 | return
202 | }
203 | this.sendMessage(2, this.msg)
204 | },
205 | sendMessage(type, msg){
206 | this.socket.send(JSON.stringify({
207 | uid: this.uid,
208 | type: type,
209 | nickname: this.nickname,
210 | msg: msg,
211 | // 增加bridge参数
212 | bridge: this.bridge
213 | }));
214 | this.msg = '';
215 | },
216 | conWebSocket(){
217 | let vm = this;
218 | if(window.WebSocket){
219 | vm.socket = new WebSocket('ws://localhost:8001');
220 | let socket = vm.socket;
221 |
222 | socket.onopen = function(e){
223 | console.log("连接服务器成功");
224 | if(!vm.uid){
225 | ...
226 | }
227 | // 这里将sendMessage方法if外面
228 | vm.sendMessage(1)
229 | }
230 | socket.onclose = function(e){
231 | console.log("服务器关闭");
232 | }
233 | socket.onerror = function(){
234 | console.log("连接出错");
235 | }
236 | // 接收服务器的消息
237 | socket.onmessage = function(e){
238 | let message = JSON.parse(e.data);
239 | vm.messageList.push(message);
240 | if(message.users) {
241 | vm.users = message.users;
242 | }
243 | }
244 | }
245 | },
246 | login(){
247 | ...
248 | }
249 | }
250 | }
251 | ```
252 |
253 | > 如果上方代码阅读体验太差,可以看下方图或者直接到文章最下方,点击了解更多阅读:
254 |
255 | 
256 |
257 | 
258 |
259 |
260 |
261 | **上方...的代码区域都是和第二篇文章一样的地方,所有就省略了。**
262 |
263 | 1、默认是群发,即`bridge`是空数组,向所有用户发送消息
264 | 2、点击用户列表,赋予`bridge`当前用户uid,和需要对话的uid。
265 | 3、在第二篇文章中,渲染的消息列表是`messageList`。现在不是,是通过计算属性`computed`,只需要`bridge`相等的消息,得出`currentMessage`当前对话的消息列表
266 | 4、因为所有消息都是通过后台socket返回,也不需要考虑发送者/接收者是谁,判断`bridge`是否相等,可以用`sort()`方法排序并转换成字符串后进行对比。
267 |
268 |
269 | ## 快速预览效果
270 |
271 | 
272 |
273 |
274 | 
275 |
276 | 
277 |
278 | ## 总结
279 | 一对一和一对多的核心,就是知道是那个用户与那个用户对话。当前目前一对多是不用考虑,因为是写死的,所有用户,后面来做不同群,随意加群聊天,就需要考虑了。也就是服务端的conn不要弄错,不然收不到消息也接收不到消息。
280 |
281 |
282 |
283 | 源码地址:[源码地址](https://github.com/javanf/web-im)
284 |
285 |
--------------------------------------------------------------------------------
/4.md:
--------------------------------------------------------------------------------
1 | > Node + WebSocket + Vue 一对一、一对多聊天室消息已读未读 - 第四章
2 |
3 |
4 | ## 前言
5 |
6 | 
7 |
8 | 这篇文章非常的短小,在之前文章基础上就实现一个非常小的功能点,消息已读和未读。如果您还没有看过之前的文字,请点击下方链接查看!
9 | 推荐文章:
10 |
11 | [《Nodejs + WebSocket简单介绍及示例 - 第一章》](https://www.toutiao.com/i6683747519056314892/)
12 | [《Nodejs + WebSocket + Vue 实现多人聊天室WebIM功能 - 第二章》](https://www.toutiao.com/i6685131748478550535/)
13 | [《Nodejs + WebSocket + Vue 一对一、一对多聊天室 - 第三章》](https://www.toutiao.com/i6685257409994162696/)
14 |
15 |
16 |
17 | ## WebSocket客户端UI界面更改
18 |
19 | ```html
20 | ...
21 |
22 |
群1
23 | {{getMsgNum()}}
24 |
25 |
26 | {{item.nickname}}
27 | {{getMsgNum(item)}}
28 |
29 |
30 | ...
31 | ```
32 |
33 | 这里就加了一个非常小的改动,加了一个`tips-num`tips,先展示未读消息。
34 |
35 | ## WebSocket服务端
36 | ```javascript
37 | ...
38 | boardcast({
39 | type: 2,
40 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
41 | msg: obj.msg,
42 | uid: obj.uid,
43 | nickname: obj.nickname,
44 | // 增加参数
45 | bridge: obj.bridge,
46 | status: 1
47 | });
48 | ...
49 | ```
50 | 服务端就在发送消息的地方增加一个字段,`status:1`来表示未读。
51 |
52 |
53 | ## WebSocket客户端
54 |
55 | 由UI界面的代码可以看出,我们调用了一个`getMsgNum`方法来展示未读消息数量。所以我们客户端只需要在原来的基础上,添加一个获取未读消息数量的方法即可。
56 | ```javascript
57 | export default {
58 | ...
59 | data(){
60 | ...
61 | },
62 | mounted() {
63 | ...
64 | },
65 | computed: {
66 | currentMessage() {
67 | let vm = this;
68 | let data = vm.messageList.filter(item=>{
69 | return item.bridge.sort().join(',') == vm.bridge.sort().join(',')
70 | })
71 | data.map(item=>{
72 | item.status = 0
73 | return item;
74 | })
75 | return data;
76 | }
77 | },
78 | methods: {
79 | getMsgNum(user){
80 | if(!user){
81 | return this.messageList.filter(item=>{
82 | return !item.bridge.length && item.status === 1
83 | }).length
84 | }
85 | return this.messageList.filter(item=>{
86 | return item.bridge.length && item.uid === user.uid && item.status === 1
87 | }).length
88 | }
89 | ...
90 | }
91 | }
92 | ```
93 |
94 | **上方...的代码区域都是和前面文章一样的地方,所有就省略了。**
95 |
96 | 1、参数`user`没有值时,表示是获取群消息未读,判断`messageList`里面的没有`bridge`(即是群聊消息),并且`status`为1(即未读)
97 | 2、如果有`user`时,获取对应用户未读消息,判断`messageList`里面的有`bridge`(即是用户对话消息)、`uid`相等,并且`status`为1(即未读)
98 | 3、打开的是当前对话,即将当前对话的消息状态`status`改为0(已读)
99 | ```javascript
100 | data.map(item=>{
101 | item.status = 0
102 | return item;
103 | })
104 | ```
105 |
106 | ## 快速预览效果
107 |
108 | 
109 |
110 |
111 | 
112 |
113 |
114 | ## 总结
115 | 消息未读,主要是判断状态,然后搞清楚对象,是谁发的消息没有读。已读,就很简单了,就是当前展示的消息列表都改成已读,所以直接把`currentMessage`列表的消息改成已读即可。
116 |
117 |
118 |
119 | 源码地址:[源码地址](https://github.com/javanf/web-im)
120 |
121 |
--------------------------------------------------------------------------------
/5.md:
--------------------------------------------------------------------------------
1 | > Node + WebSocket + Vue 聊天室创建群聊/加入群聊功能 - 第五章
2 |
3 |
4 | ## 前言
5 |
6 | 
7 |
8 | 本次算是做了一个小小的专题吧,“Nodejs + WebSocket + Vue实现聊天室功能”,目前还在一步一步推进,之前已经可以一对一、一对多聊天了,今天就来创建群聊组,加入群聊组等,同时项目中加入了全局message提示框,有兴趣的可以去看看。
9 |
10 | 如果您还没有看过之前的文字,请点击下方链接查看!
11 | 推荐文章:
12 |
13 | [《Nodejs + WebSocket简单介绍及示例 - 第一章》](https://www.toutiao.com/i6683747519056314892/)
14 | [《Nodejs + WebSocket + Vue 实现多人聊天室WebIM功能 - 第二章》](https://www.toutiao.com/i6685131748478550535/)
15 | [《Nodejs + WebSocket + Vue 一对一、一对多聊天室 - 第三章》](https://www.toutiao.com/i6685257409994162696/)
16 | [《Node + WebSocket + Vue 一对一、一对多聊天室消息已读未读 - 第四章》](https://www.toutiao.com/i6685523858054709763/)
17 |
18 |
19 | ## WebSocket服务端
20 | 做出调整的地方有注释,后面也会做出讲解。
21 | ```javascript
22 | ...
23 |
24 | let users = [];
25 | let conns = {};
26 | // 群组数组,多个群
27 | let groups = [];
28 |
29 | function boardcast(obj) {
30 | if(obj.bridge && obj.bridge.length){
31 | obj.bridge.forEach(item=>{
32 | conns[item].sendText(JSON.stringify(obj));
33 | })
34 | return;
35 | }
36 | // 如果是有groupId代表是群消息
37 | if (obj.groupId) {
38 | // 找到对应群
39 | group = groups.filter(item=>{
40 | return item.id === obj.groupId
41 | })[0];
42 | // 变量群里面的任意,发送消息
43 | group.users.forEach(item=>{
44 | conns[item.uid].sendText(JSON.stringify(obj));
45 | })
46 | return;
47 | }
48 |
49 | server.connections.forEach((conn, index) => {
50 | conn.sendText(JSON.stringify(obj));
51 | })
52 | }
53 |
54 | var server = ws.createServer(function(conn){
55 | conn.on("text", function (obj) {
56 | obj = JSON.parse(obj);
57 | conns[''+obj.uid+''] = conn;
58 | // 由原来的if改成switch case
59 | switch(obj.type){
60 | // 创建连接
61 | case 1:
62 | ...
63 | break;
64 | // 创建群
65 | case 10:
66 | // 向groups push数据,同时默认把创建者加入到该群
67 | groups.push({
68 | id: moment().valueOf(),
69 | name: obj.groupName,
70 | users: [{
71 | uid: obj.uid,
72 | nickname: obj.nickname
73 | }]
74 | })
75 | // 把创建的消息推送给所有用户
76 | boardcast({
77 | type: 1,
78 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
79 | msg: obj.nickname+'创建了群' + obj.groupName,
80 | users: users,
81 | groups: groups,
82 | uid: obj.uid,
83 | nickname: obj.nickname,
84 | bridge: obj.bridge
85 | });
86 | break;
87 | // 加入群
88 | case 20:
89 | // 根据传入的groupId找到对应的群
90 | let group = groups.filter(item=>{
91 | return item.id === obj.groupId
92 | })[0]
93 | // 向对应的群成员users push数据
94 | group.users.push({
95 | uid: obj.uid,
96 | nickname: obj.nickname
97 | })
98 | boardcast({
99 | type: 1,
100 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
101 | msg: obj.nickname+'加入了群' + obj.groupName,
102 | users: users,
103 | groups: groups,
104 | uid: obj.uid,
105 | nickname: obj.nickname,
106 | bridge: obj.bridge
107 | });
108 | break;
109 | // 发送消息
110 | default:
111 | boardcast({
112 | type: 2,
113 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
114 | msg: obj.msg,
115 | uid: obj.uid,
116 | nickname: obj.nickname,
117 | bridge: obj.bridge,
118 | // 添加groupId参数,有是群发,没有是一对一
119 | groupId: obj.groupId,
120 | status: 1
121 | });
122 | break;
123 | }
124 | })
125 | ...
126 | }).listen(8001)
127 | ...
128 | ```
129 | ok, 通过上方的代码,以及注释,相信很多小伙伴应该都明白了,这里简单讲解一下。
130 |
131 | 根据前端页面传入的type,来判断是什么操作?
132 |
133 | 1、如果是10,创建群聊,我们就将群名称,以及生成的群id,存入groups里面,并且把创建群聊的人默认加入到群
134 | 2、如果是20,加入群聊,我们根据要加入的群id,找到对应的群,并把需要加入的人,加入到群
135 | 3、发送消息,判断是否有群id,如果没有表示一对一,逻辑不变。如果有群id,则去groups里面找到对应的群,并拿出群下面所有的user,根据id,找到对应的conn(用户连接),发送消息。
136 |
137 |
138 | ## WebSocket客户端JS
139 | 我们也主要研究变的地方,没有变的通过...表示。同时,如果您想看完整代码,可以去文章最下方“了解更多”,来获取源码查看。
140 |
141 | ```javascript
142 | ...
143 |
144 | export default {
145 | ...
146 | data(){
147 | return {
148 | title: '请选择群或者人员进行聊天',
149 | ...
150 | groups: [], // 群组
151 | groupId: '' // 当前群聊id
152 | }
153 | },
154 | mounted() {
155 | ... // 不变
156 | },
157 | computed: {
158 | currentMessage() {
159 | let vm = this;
160 | let data = vm.messageList.filter(item=>{
161 | if(this.groupId) {
162 | return item.groupId === this.groupId
163 | } else if(item.bridge.length){
164 | return item.bridge.sort().join(',') == vm.bridge.sort().join(',')
165 | }
166 | })
167 | data.map(item=>{
168 | item.status = 0
169 | return item;
170 | })
171 | return data;
172 | }
173 | },
174 | methods: {
175 | addGroup(item){
176 | this.socket.send(JSON.stringify({
177 | uid: this.uid,
178 | type: 20,
179 | nickname: this.nickname,
180 | groupId: item.id,
181 | groupName: item.name,
182 | bridge: []
183 | }));
184 | this.$message({type: 'success', message: `成功加入${item.name}群`})
185 | },
186 | checkUserIsGroup (item) {
187 | return item.users.some(item=>{
188 | return item.uid === this.uid
189 | })
190 | },
191 | createGroup(){
192 | this.socket.send(JSON.stringify({
193 | uid: this.uid,
194 | type: 10,
195 | nickname: this.nickname,
196 | groupName: this.groupName,
197 | bridge: []
198 | }));
199 | },
200 | getGroupMsgNum(group){
201 | return this.messageList.filter(item=>{
202 | return item.groupId === group.id && item.status === 1
203 | }).length
204 | },
205 | getUserMsgNum(user){
206 | return this.messageList.filter(item=>{
207 | return item.bridge.length && item.uid === user.uid && item.status === 1
208 | }).length
209 | },
210 | triggerGroup(item) {
211 | let issome = item.users.some(item=>{
212 | return item.uid === this.uid
213 | })
214 | if(!issome){
215 | this.$message({type: 'error', message: `您还不是${item.name}群成员`})
216 | return
217 | }
218 | this.bridge = [];
219 | this.groupId = item.id;
220 | this.title = `和${item.name}群成员聊天`;
221 | },
222 | triggerPersonal(item) {
223 | if(this.uid === item.uid){
224 | return;
225 | }
226 | this.groupId = '';
227 | this.bridge = [this.uid, item.uid];
228 | this.title = `和${item.nickname}聊天`;
229 | },
230 | send(){
231 | if(!this.msg){
232 | return
233 | }
234 | if(!this.bridge.length && !this.groupId){
235 | this.$message({type: 'error', message: '请选择发送人或者群'})
236 | return;
237 | }
238 | this.sendMessage(2, this.msg)
239 | },
240 | sendMessage(type, msg){
241 | this.socket.send(JSON.stringify({
242 | uid: this.uid,
243 | type: type,
244 | nickname: this.nickname,
245 | msg: msg,
246 | bridge: this.bridge,
247 | groupId: this.groupId // 如果群聊id,可能为空(一对一)
248 | }));
249 | this.msg = '';
250 | },
251 | conWebSocket(){
252 | let vm = this;
253 | if(window.WebSocket){
254 | vm.socket = new WebSocket('ws://localhost:8001');
255 | let socket = vm.socket;
256 | ...
257 | // 接收服务器的消息
258 | socket.onmessage = function(e){
259 | let message = JSON.parse(e.data);
260 | vm.messageList.push(message);
261 | if(message.users) {
262 | vm.users = message.users;
263 | }
264 | if (message.groups){
265 | vm.groups = message.groups;
266 | }
267 | }
268 | }
269 | },
270 | login(){
271 | ...
272 | }
273 | }
274 | }
275 | ```
276 |
277 | ## WebSocket客户端HTML
278 | ```html
279 | ...
280 |
281 |
新建群
282 |
283 | {{item.name}}
284 | {{getGroupMsgNum(item)}}
285 | +
286 |
287 |
288 | {{item.nickname}}
289 | {{getUserMsgNum(item)}}
290 |
291 |
292 | ...
293 | ```
294 | 这里增加了遍历groups群里,同时判断当前用户是否在群里里面,没有则有一个加入按钮。
295 |
296 | ## 解析客户端代码
297 | 1、`socket.onmessage`来判断是否有groups群组,有就赋值给groups
298 | 2、创建群组,输入名称,确认后,发送给服务端,告诉是创建群组,已经创建人员、群组名称等
299 | 3、加入群组,发送给服务端要加入群组id,当前用户id
300 | 4、获取群未读消息数量和之前类似,只需要判断,是群消息,并且`status`为1
301 | 5、同时页面校验等做了一些处理,判断用户是否在群里面,不在不能发送消息;发消息前需选择用户或者群;
302 |
303 |
304 | ## 快速预览效果
305 |
306 | 
307 |
308 |
309 | 
310 |
311 |
312 | 
313 |
314 |
315 | 
316 |
317 | 
318 |
319 |
320 |
321 | 源码地址:[源码地址](https://github.com/javanf/web-im)
322 |
323 |
--------------------------------------------------------------------------------
/6.md:
--------------------------------------------------------------------------------
1 | > Node+WebSocket+Vue聊天室: 界面美化,代码优化 - 第六章
2 |
3 |
4 | ## 前言
5 |
6 | 
7 |
8 | 感谢你再次点开了我,只能说明你是喜欢我的,对不对?哈哈,开个玩笑。
9 |
10 | 今天主要是把之前的聊天室界面美化一下,不至于太难看,同时也对代码做了一些优化。具体细节请看详细内容。
11 |
12 | 并且可以线上体验了:[体验地址](http://im.javanx.cn/#/)
13 |
14 | 如果您还没有看过之前的文字,请点击下方链接查看!
15 | 推荐文章:
16 |
17 | [《Nodejs + WebSocket简单介绍及示例 - 第一章》](https://www.toutiao.com/i6683747519056314892/)
18 | [《Nodejs + WebSocket + Vue 实现多人聊天室WebIM功能 - 第二章》](https://www.toutiao.com/i6685131748478550535/)
19 | [《Nodejs + WebSocket + Vue 一对一、一对多聊天室 - 第三章》](https://www.toutiao.com/i6685257409994162696/)
20 | [《Node + WebSocket + Vue 一对一、一对多聊天室消息已读未读 - 第四章》](https://www.toutiao.com/i6685523858054709763/)
21 | [《Node + WebSocket + Vue 聊天室创建群聊/加入群聊功能 - 第五章》](http://toutiao.com/item/6688204175710355975/)
22 |
23 |
24 | ## 客户端HTML代码优化
25 |
26 | 
27 |
28 | 页面先分为左右布局,然后左/右里面再分为上中下布局。
29 |
30 | 很自然,我们想到了`flex`布局,Flex是Flexible Box的缩写,意为”弹性布局”,用来为盒状模型提供最大的灵活性。
31 |
32 | ```html
33 | ...
34 |
35 |
36 |
37 |
40 |
41 | ...
42 |
43 |
46 |
47 |
48 |
49 |
50 |
51 | ...
52 |
53 |
56 |
57 |
58 | ...
59 | ```
60 |
61 |
62 | css样式是用stylus书写的,有些初学的小伙伴应该有点点不是很明白,但是大致能懂,就是把嵌套的书写,使其看起来更容易阅读、维护。
63 |
64 | 如果对flex、和stylus不是很明白的小伙伴,可以留言区留言,后期看情况出更详细的教程,这里就不啰嗦了。
65 |
66 | ```stylus
67 | .web-im
68 | display flex
69 | .left
70 | width 220px
71 | .right
72 | flex 1
73 | .content
74 | display: flex;
75 | flex-direction: row;
76 | flex: 1;
77 | box-sizing: border-box;
78 | min-width: 0;
79 | flex-direction: column;
80 | .header
81 | box-shadow 1px -1px 2px 2px #eee
82 | line-height 40px
83 | height 40px
84 | font-size 24px
85 | z-index 10
86 | background #fff
87 | .body
88 | flex 1
89 | overflow-y auto
90 | box-shadow 1px 1px 1px #eee
91 | .footer
92 | box-shadow 1px 1px 8px #eee
93 | height 60px
94 |
95 | ```
96 |
97 | ## WebSocket客户端JS
98 | 我们主要研究变的地方,没有变的通过...表示。同时,如果您想看完整代码,可以去文章最下方“了解更多”,来获取源码查看。
99 |
100 | ```javascript
101 | ...
102 | export default {
103 | ...
104 | mounted() {
105 | ...
106 | // 监听页面刷新,关闭事件,退出聊天室
107 | window.onbeforeunload = function (e) {
108 | vm.socket.send(JSON.stringify({
109 | uid: vm.uid,
110 | type: 2,
111 | nickname: vm.nickname,
112 | bridge: []
113 | }));
114 | }
115 | },
116 | computed: {
117 | // 当前展示的消息列表
118 | currentMessage() {
119 | let vm = this;
120 | let data = vm.messageList.filter(item=>{
121 | if(item.type === 1) {
122 | return item;
123 | } else if(this.groupId) {
124 | return item.groupId === this.groupId
125 | } else if(item.bridge.length){
126 | return item.bridge.sort().join(',') == vm.bridge.sort().join(',')
127 | }
128 | })
129 | data.map(item=>{
130 | item.status = 0
131 | return item;
132 | })
133 | return data;
134 | },
135 | // 当前群组列表
136 | currentGroups() {
137 | let vm = this;
138 | vm.groups.map(group=>{
139 | // 找出群组对应未读消息
140 | group.unread = this.messageList.filter(item=>{
141 | return item.groupId === group.id && item.status === 1
142 | }).length
143 | return group;
144 | })
145 | return vm.groups;
146 | },
147 | // 群组列表是否有未读消息
148 | groupsUnRead(){
149 | return this.messageList.some(item=>{
150 | return item.groupId && item.status === 1
151 | })
152 | },
153 | // 联系人列表是否有未读消息
154 | usersUnRead(){
155 | return this.messageList.some(item=>{
156 | return item.bridge.length && item.status === 1
157 | })
158 | },
159 | // 当前联系人列表
160 | currentUserList() {
161 | let vm = this;
162 | vm.users.map(user=>{
163 | // 找出联系人对应未读消息
164 | user.unread = this.messageList.filter(item=>{
165 | return item.bridge.length && item.uid === user.uid && item.status === 1
166 | }).length
167 | return user;
168 | })
169 | return vm.users;
170 | }
171 | },
172 | methods: {
173 | ...
174 | conWebSocket(){
175 | let vm = this;
176 | if(window.WebSocket){
177 | ...
178 | socket.onmessage = function(e){
179 | ...
180 | // 消息列表滚动条始终在最底部
181 | vm.$nextTick(function(){
182 | var div = document.getElementById('im-record');
183 | div.scrollTop = div.scrollHeight;
184 | })
185 | }
186 | }
187 | }
188 | ...
189 | }
190 | }
191 | ```
192 |
193 | 这次代码优化,主要是在计算属性上面做了大的调整。之前都是用方法来获取未读已读等,现在直接计算属性先一步计算,然后渲染到页面。
194 |
195 | ## WebSocket服务端
196 | ```javascript
197 | ...
198 | // 注销
199 | case 2:
200 | delete conns[''+obj.uid+''];
201 | users.map((item, index)=>{
202 | if(item.uid === obj.uid){
203 | item.status = 0;
204 | }
205 | return item;
206 | })
207 | boardcast({
208 | type: 1,
209 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
210 | msg: obj.nickname+'退出了聊天室',
211 | users: users,
212 | groups: groups,
213 | uid: obj.uid,
214 | nickname: obj.nickname,
215 | bridge: []
216 | });
217 | break;
218 | ...
219 | ```
220 |
221 | 服务端主要增加了一个注销功能,用户下线。
222 | 同时,之前type=2是发送消息,现在改成了100是发送消息,2是用户下线。
223 |
224 |
225 |
226 | ## 快速预览效果
227 |
228 | 
229 |
230 |
231 | 
232 |
233 | 源码地址:[源码地址](https://github.com/javanf/web-im)
234 | 体验地址:[体验地址](http://im.javanx.cn/#/)
235 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Nodejs + WebSocket + Vue 聊天室WebIM
2 |
3 | ## 快速体验
4 |
5 | ``` bash
6 | # install模块
7 | npm install
8 |
9 | # 运行客户端
10 | npm run dev
11 |
12 | # 运行服务端server/index.js
13 | node index.js
14 | ```
15 |
16 | ## 预览
17 |
18 | 
19 |
20 | ## 演示地址
21 |
22 | 在线体验地址:[Web IM](http://im.javanx.cn/#/)
--------------------------------------------------------------------------------
/build/build.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | require('./check-versions')()
3 |
4 | process.env.NODE_ENV = 'production'
5 |
6 | const ora = require('ora')
7 | const rm = require('rimraf')
8 | const path = require('path')
9 | const chalk = require('chalk')
10 | const webpack = require('webpack')
11 | const config = require('../config')
12 | const webpackConfig = require('./webpack.prod.conf')
13 |
14 | const spinner = ora('building for production...')
15 | spinner.start()
16 |
17 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
18 | if (err) throw err
19 | webpack(webpackConfig, (err, stats) => {
20 | spinner.stop()
21 | if (err) throw err
22 | process.stdout.write(stats.toString({
23 | colors: true,
24 | modules: false,
25 | children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
26 | chunks: false,
27 | chunkModules: false
28 | }) + '\n\n')
29 |
30 | if (stats.hasErrors()) {
31 | console.log(chalk.red(' Build failed with errors.\n'))
32 | process.exit(1)
33 | }
34 |
35 | console.log(chalk.cyan(' Build complete.\n'))
36 | console.log(chalk.yellow(
37 | ' Tip: built files are meant to be served over an HTTP server.\n' +
38 | ' Opening index.html over file:// won\'t work.\n'
39 | ))
40 | })
41 | })
42 |
--------------------------------------------------------------------------------
/build/check-versions.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const chalk = require('chalk')
3 | const semver = require('semver')
4 | const packageConfig = require('../package.json')
5 | const shell = require('shelljs')
6 |
7 | function exec (cmd) {
8 | return require('child_process').execSync(cmd).toString().trim()
9 | }
10 |
11 | const versionRequirements = [
12 | {
13 | name: 'node',
14 | currentVersion: semver.clean(process.version),
15 | versionRequirement: packageConfig.engines.node
16 | }
17 | ]
18 |
19 | if (shell.which('npm')) {
20 | versionRequirements.push({
21 | name: 'npm',
22 | currentVersion: exec('npm --version'),
23 | versionRequirement: packageConfig.engines.npm
24 | })
25 | }
26 |
27 | module.exports = function () {
28 | const warnings = []
29 |
30 | for (let i = 0; i < versionRequirements.length; i++) {
31 | const mod = versionRequirements[i]
32 |
33 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
34 | warnings.push(mod.name + ': ' +
35 | chalk.red(mod.currentVersion) + ' should be ' +
36 | chalk.green(mod.versionRequirement)
37 | )
38 | }
39 | }
40 |
41 | if (warnings.length) {
42 | console.log('')
43 | console.log(chalk.yellow('To use this template, you must update following to modules:'))
44 | console.log()
45 |
46 | for (let i = 0; i < warnings.length; i++) {
47 | const warning = warnings[i]
48 | console.log(' ' + warning)
49 | }
50 |
51 | console.log()
52 | process.exit(1)
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/build/utils.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const path = require('path')
3 | const config = require('../config')
4 | const ExtractTextPlugin = require('extract-text-webpack-plugin')
5 | const packageConfig = require('../package.json')
6 |
7 | exports.assetsPath = function (_path) {
8 | const assetsSubDirectory = process.env.NODE_ENV === 'production'
9 | ? config.build.assetsSubDirectory
10 | : config.dev.assetsSubDirectory
11 |
12 | return path.posix.join(assetsSubDirectory, _path)
13 | }
14 |
15 | exports.cssLoaders = function (options) {
16 | options = options || {}
17 |
18 | const cssLoader = {
19 | loader: 'css-loader',
20 | options: {
21 | sourceMap: options.sourceMap
22 | }
23 | }
24 |
25 | const postcssLoader = {
26 | loader: 'postcss-loader',
27 | options: {
28 | sourceMap: options.sourceMap
29 | }
30 | }
31 |
32 | const stylusLoader = {
33 | loader: 'stylus-loader',
34 | options: {
35 | sourceMap: options.sourceMap
36 | }
37 | }
38 |
39 | // generate loader string to be used with extract text plugin
40 | function generateLoaders (loader, loaderOptions) {
41 | const loaders = options.usePostCSS ? [stylusLoader, cssLoader, postcssLoader] : [cssLoader]
42 |
43 | if (loader) {
44 | loaders.push({
45 | loader: loader + '-loader',
46 | options: Object.assign({}, loaderOptions, {
47 | sourceMap: options.sourceMap
48 | })
49 | })
50 | }
51 |
52 | // Extract CSS when that option is specified
53 | // (which is the case during production build)
54 | if (options.extract) {
55 | return ExtractTextPlugin.extract({
56 | use: loaders,
57 | fallback: 'vue-style-loader'
58 | })
59 | } else {
60 | return ['vue-style-loader'].concat(loaders)
61 | }
62 | }
63 |
64 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html
65 | return {
66 | css: generateLoaders(),
67 | postcss: generateLoaders(),
68 | less: generateLoaders('less'),
69 | sass: generateLoaders('sass', { indentedSyntax: true }),
70 | scss: generateLoaders('sass'),
71 | stylus: generateLoaders('stylus'),
72 | styl: generateLoaders('stylus')
73 | }
74 | }
75 |
76 | // Generate loaders for standalone style files (outside of .vue)
77 | exports.styleLoaders = function (options) {
78 | const output = []
79 | const loaders = exports.cssLoaders(options)
80 |
81 | for (const extension in loaders) {
82 | const loader = loaders[extension]
83 | output.push({
84 | test: new RegExp('\\.' + extension + '$'),
85 | use: loader
86 | })
87 | }
88 |
89 | return output
90 | }
91 |
92 | exports.createNotifierCallback = () => {
93 | const notifier = require('node-notifier')
94 |
95 | return (severity, errors) => {
96 | if (severity !== 'error') return
97 |
98 | const error = errors[0]
99 | const filename = error.file && error.file.split('!').pop()
100 |
101 | notifier.notify({
102 | title: packageConfig.name,
103 | message: severity + ': ' + error.name,
104 | subtitle: filename || '',
105 | icon: path.join(__dirname, 'logo.png')
106 | })
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/build/vue-loader.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const utils = require('./utils')
3 | const config = require('../config')
4 | const isProduction = process.env.NODE_ENV === 'production'
5 | const sourceMapEnabled = isProduction
6 | ? config.build.productionSourceMap
7 | : config.dev.cssSourceMap
8 |
9 | module.exports = {
10 | loaders: utils.cssLoaders({
11 | sourceMap: sourceMapEnabled,
12 | extract: false
13 | }),
14 | cssSourceMap: sourceMapEnabled,
15 | cacheBusting: config.dev.cacheBusting,
16 | transformToRequire: {
17 | video: ['src', 'poster'],
18 | source: 'src',
19 | img: 'src',
20 | image: 'xlink:href'
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/build/webpack.base.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const path = require('path')
3 | const utils = require('./utils')
4 | const config = require('../config')
5 | const vueLoaderConfig = require('./vue-loader.conf')
6 |
7 | function resolve (dir) {
8 | return path.join(__dirname, '..', dir)
9 | }
10 |
11 |
12 |
13 | module.exports = {
14 | context: path.resolve(__dirname, '../'),
15 | entry: {
16 | app: './src/main.js'
17 | },
18 | output: {
19 | path: config.build.assetsRoot,
20 | filename: '[name].js',
21 | publicPath: process.env.NODE_ENV === 'production'
22 | ? config.build.assetsPublicPath
23 | : config.dev.assetsPublicPath
24 | },
25 | resolve: {
26 | extensions: ['.js', '.vue', '.json'],
27 | alias: {
28 | 'vue$': 'vue/dist/vue.esm.js',
29 | '@': resolve('src'),
30 | }
31 | },
32 | module: {
33 | rules: [
34 | {
35 | test: /\.vue$/,
36 | loader: 'vue-loader',
37 | options: vueLoaderConfig
38 | },
39 | {
40 | test: /\.js$/,
41 | loader: 'babel-loader',
42 | include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
43 | },
44 | {
45 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
46 | loader: 'url-loader',
47 | options: {
48 | limit: 10000,
49 | name: utils.assetsPath('img/[name].[hash:7].[ext]')
50 | }
51 | },
52 | {
53 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
54 | loader: 'url-loader',
55 | options: {
56 | limit: 10000,
57 | name: utils.assetsPath('media/[name].[hash:7].[ext]')
58 | }
59 | },
60 | {
61 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
62 | loader: 'url-loader',
63 | options: {
64 | limit: 10000,
65 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
66 | }
67 | }
68 | ]
69 | },
70 | node: {
71 | // prevent webpack from injecting useless setImmediate polyfill because Vue
72 | // source contains it (although only uses it if it's native).
73 | setImmediate: false,
74 | // prevent webpack from injecting mocks to Node native modules
75 | // that does not make sense for the client
76 | dgram: 'empty',
77 | fs: 'empty',
78 | net: 'empty',
79 | tls: 'empty',
80 | child_process: 'empty'
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/build/webpack.dev.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const utils = require('./utils')
3 | const webpack = require('webpack')
4 | const config = require('../config')
5 | const merge = require('webpack-merge')
6 | const path = require('path')
7 | const baseWebpackConfig = require('./webpack.base.conf')
8 | const CopyWebpackPlugin = require('copy-webpack-plugin')
9 | const HtmlWebpackPlugin = require('html-webpack-plugin')
10 | const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
11 | const portfinder = require('portfinder')
12 |
13 | const HOST = process.env.HOST
14 | const PORT = process.env.PORT && Number(process.env.PORT)
15 |
16 | const devWebpackConfig = merge(baseWebpackConfig, {
17 | module: {
18 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
19 | },
20 | // cheap-module-eval-source-map is faster for development
21 | devtool: config.dev.devtool,
22 |
23 | // these devServer options should be customized in /config/index.js
24 | devServer: {
25 | clientLogLevel: 'warning',
26 | historyApiFallback: {
27 | rewrites: [
28 | { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
29 | ],
30 | },
31 | hot: true,
32 | contentBase: false, // since we use CopyWebpackPlugin.
33 | compress: true,
34 | host: HOST || config.dev.host,
35 | port: PORT || config.dev.port,
36 | open: config.dev.autoOpenBrowser,
37 | overlay: config.dev.errorOverlay
38 | ? { warnings: false, errors: true }
39 | : false,
40 | publicPath: config.dev.assetsPublicPath,
41 | proxy: config.dev.proxyTable,
42 | quiet: true, // necessary for FriendlyErrorsPlugin
43 | watchOptions: {
44 | poll: config.dev.poll,
45 | }
46 | },
47 | plugins: [
48 | new webpack.DefinePlugin({
49 | 'process.env': require('../config/dev.env')
50 | }),
51 | new webpack.HotModuleReplacementPlugin(),
52 | new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
53 | new webpack.NoEmitOnErrorsPlugin(),
54 | // https://github.com/ampedandwired/html-webpack-plugin
55 | new HtmlWebpackPlugin({
56 | filename: 'index.html',
57 | template: 'index.html',
58 | inject: true
59 | }),
60 | // copy custom static assets
61 | new CopyWebpackPlugin([
62 | {
63 | from: path.resolve(__dirname, '../static'),
64 | to: config.dev.assetsSubDirectory,
65 | ignore: ['.*']
66 | }
67 | ])
68 | ]
69 | })
70 |
71 | module.exports = new Promise((resolve, reject) => {
72 | portfinder.basePort = process.env.PORT || config.dev.port
73 | portfinder.getPort((err, port) => {
74 | if (err) {
75 | reject(err)
76 | } else {
77 | // publish the new Port, necessary for e2e tests
78 | process.env.PORT = port
79 | // add port to devServer config
80 | devWebpackConfig.devServer.port = port
81 |
82 | // Add FriendlyErrorsPlugin
83 | devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
84 | compilationSuccessInfo: {
85 | messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
86 | },
87 | onErrors: config.dev.notifyOnErrors
88 | ? utils.createNotifierCallback()
89 | : undefined
90 | }))
91 |
92 | resolve(devWebpackConfig)
93 | }
94 | })
95 | })
96 |
--------------------------------------------------------------------------------
/build/webpack.prod.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const path = require('path')
3 | const utils = require('./utils')
4 | const webpack = require('webpack')
5 | const config = require('../config')
6 | const merge = require('webpack-merge')
7 | const baseWebpackConfig = require('./webpack.base.conf')
8 | const CopyWebpackPlugin = require('copy-webpack-plugin')
9 | const HtmlWebpackPlugin = require('html-webpack-plugin')
10 | const ExtractTextPlugin = require('extract-text-webpack-plugin')
11 | const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
12 | const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
13 |
14 | const env = require('../config/prod.env')
15 |
16 | const webpackConfig = merge(baseWebpackConfig, {
17 | module: {
18 | rules: utils.styleLoaders({
19 | sourceMap: config.build.productionSourceMap,
20 | extract: true,
21 | usePostCSS: true
22 | })
23 | },
24 | devtool: config.build.productionSourceMap ? config.build.devtool : false,
25 | output: {
26 | path: config.build.assetsRoot,
27 | filename: utils.assetsPath('js/[name].[chunkhash].js'),
28 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
29 | },
30 | plugins: [
31 | // http://vuejs.github.io/vue-loader/en/workflow/production.html
32 | new webpack.DefinePlugin({
33 | 'process.env': env
34 | }),
35 | new UglifyJsPlugin({
36 | uglifyOptions: {
37 | compress: {
38 | warnings: false
39 | }
40 | },
41 | sourceMap: config.build.productionSourceMap,
42 | parallel: true
43 | }),
44 | // extract css into its own file
45 | new ExtractTextPlugin({
46 | filename: utils.assetsPath('css/[name].[contenthash].css'),
47 | // Setting the following option to `false` will not extract CSS from codesplit chunks.
48 | // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
49 | // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
50 | // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
51 | allChunks: true,
52 | }),
53 | // Compress extracted CSS. We are using this plugin so that possible
54 | // duplicated CSS from different components can be deduped.
55 | new OptimizeCSSPlugin({
56 | cssProcessorOptions: config.build.productionSourceMap
57 | ? { safe: true, map: { inline: false } }
58 | : { safe: true }
59 | }),
60 | // generate dist index.html with correct asset hash for caching.
61 | // you can customize output by editing /index.html
62 | // see https://github.com/ampedandwired/html-webpack-plugin
63 | new HtmlWebpackPlugin({
64 | filename: config.build.index,
65 | template: 'index.html',
66 | inject: true,
67 | minify: {
68 | removeComments: true,
69 | collapseWhitespace: true,
70 | removeAttributeQuotes: true
71 | // more options:
72 | // https://github.com/kangax/html-minifier#options-quick-reference
73 | },
74 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin
75 | chunksSortMode: 'dependency'
76 | }),
77 | // keep module.id stable when vendor modules does not change
78 | new webpack.HashedModuleIdsPlugin(),
79 | // enable scope hoisting
80 | new webpack.optimize.ModuleConcatenationPlugin(),
81 | // split vendor js into its own file
82 | new webpack.optimize.CommonsChunkPlugin({
83 | name: 'vendor',
84 | minChunks (module) {
85 | // any required modules inside node_modules are extracted to vendor
86 | return (
87 | module.resource &&
88 | /\.js$/.test(module.resource) &&
89 | module.resource.indexOf(
90 | path.join(__dirname, '../node_modules')
91 | ) === 0
92 | )
93 | }
94 | }),
95 | // extract webpack runtime and module manifest to its own file in order to
96 | // prevent vendor hash from being updated whenever app bundle is updated
97 | new webpack.optimize.CommonsChunkPlugin({
98 | name: 'manifest',
99 | minChunks: Infinity
100 | }),
101 | // This instance extracts shared chunks from code splitted chunks and bundles them
102 | // in a separate chunk, similar to the vendor chunk
103 | // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
104 | new webpack.optimize.CommonsChunkPlugin({
105 | name: 'app',
106 | async: 'vendor-async',
107 | children: true,
108 | minChunks: 3
109 | }),
110 |
111 | // copy custom static assets
112 | new CopyWebpackPlugin([
113 | {
114 | from: path.resolve(__dirname, '../static'),
115 | to: config.build.assetsSubDirectory,
116 | ignore: ['.*']
117 | }
118 | ])
119 | ]
120 | })
121 |
122 | if (config.build.productionGzip) {
123 | const CompressionWebpackPlugin = require('compression-webpack-plugin')
124 |
125 | webpackConfig.plugins.push(
126 | new CompressionWebpackPlugin({
127 | asset: '[path].gz[query]',
128 | algorithm: 'gzip',
129 | test: new RegExp(
130 | '\\.(' +
131 | config.build.productionGzipExtensions.join('|') +
132 | ')$'
133 | ),
134 | threshold: 10240,
135 | minRatio: 0.8
136 | })
137 | )
138 | }
139 |
140 | if (config.build.bundleAnalyzerReport) {
141 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
142 | webpackConfig.plugins.push(new BundleAnalyzerPlugin())
143 | }
144 |
145 | module.exports = webpackConfig
146 |
--------------------------------------------------------------------------------
/config/dev.env.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const merge = require('webpack-merge')
3 | const prodEnv = require('./prod.env')
4 |
5 | module.exports = merge(prodEnv, {
6 | NODE_ENV: '"development"'
7 | })
8 |
--------------------------------------------------------------------------------
/config/index.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | // Template version: 1.3.1
3 | // see http://vuejs-templates.github.io/webpack for documentation.
4 |
5 | const path = require('path')
6 |
7 | module.exports = {
8 | dev: {
9 |
10 | // Paths
11 | assetsSubDirectory: 'static',
12 | assetsPublicPath: '/',
13 | proxyTable: {},
14 |
15 | // Various Dev Server settings
16 | host: 'localhost', // can be overwritten by process.env.HOST
17 | port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
18 | autoOpenBrowser: false,
19 | errorOverlay: true,
20 | notifyOnErrors: true,
21 | poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
22 |
23 |
24 | /**
25 | * Source Maps
26 | */
27 |
28 | // https://webpack.js.org/configuration/devtool/#development
29 | devtool: 'cheap-module-eval-source-map',
30 |
31 | // If you have problems debugging vue-files in devtools,
32 | // set this to false - it *may* help
33 | // https://vue-loader.vuejs.org/en/options.html#cachebusting
34 | cacheBusting: true,
35 |
36 | cssSourceMap: true
37 | },
38 |
39 | build: {
40 | // Template for index.html
41 | index: path.resolve(__dirname, '../dist/index.html'),
42 |
43 | // Paths
44 | assetsRoot: path.resolve(__dirname, '../dist'),
45 | assetsSubDirectory: 'static',
46 | assetsPublicPath: '/',
47 |
48 | /**
49 | * Source Maps
50 | */
51 |
52 | productionSourceMap: true,
53 | // https://webpack.js.org/configuration/devtool/#production
54 | devtool: '#source-map',
55 |
56 | // Gzip off by default as many popular static hosts such as
57 | // Surge or Netlify already gzip all static assets for you.
58 | // Before setting to `true`, make sure to:
59 | // npm install --save-dev compression-webpack-plugin
60 | productionGzip: false,
61 | productionGzipExtensions: ['js', 'css'],
62 |
63 | // Run the build command with an extra argument to
64 | // View the bundle analyzer report after build finishes:
65 | // `npm run build --report`
66 | // Set to `true` or `false` to always turn it on or off
67 | bundleAnalyzerReport: process.env.npm_config_report
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/config/prod.env.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | module.exports = {
3 | NODE_ENV: '"production"'
4 | }
5 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Web IM - Nodejs + WebSocket + Vue聊天室
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "web-im",
3 | "version": "1.0.0",
4 | "description": "Nodejs + WebSocket Web Im",
5 | "author": "javanx",
6 | "private": true,
7 | "scripts": {
8 | "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
9 | "start": "npm run dev",
10 | "build": "node build/build.js"
11 | },
12 | "dependencies": {
13 | "moment": "^2.24.0",
14 | "nodejs-websocket": "^1.7.2",
15 | "stylus": "^0.54.5",
16 | "stylus-loader": "^3.0.2",
17 | "vue": "^2.5.2",
18 | "vue-router": "^3.0.1"
19 | },
20 | "devDependencies": {
21 | "autoprefixer": "^7.1.2",
22 | "babel-core": "^6.22.1",
23 | "babel-helper-vue-jsx-merge-props": "^2.0.3",
24 | "babel-loader": "^7.1.1",
25 | "babel-plugin-syntax-jsx": "^6.18.0",
26 | "babel-plugin-transform-runtime": "^6.22.0",
27 | "babel-plugin-transform-vue-jsx": "^3.5.0",
28 | "babel-preset-env": "^1.3.2",
29 | "babel-preset-stage-2": "^6.22.0",
30 | "chalk": "^2.0.1",
31 | "copy-webpack-plugin": "^4.0.1",
32 | "css-loader": "^0.28.0",
33 | "extract-text-webpack-plugin": "^3.0.0",
34 | "file-loader": "^1.1.4",
35 | "friendly-errors-webpack-plugin": "^1.6.1",
36 | "html-webpack-plugin": "^2.30.1",
37 | "node-notifier": "^5.1.2",
38 | "optimize-css-assets-webpack-plugin": "^3.2.0",
39 | "ora": "^1.2.0",
40 | "portfinder": "^1.0.13",
41 | "postcss-import": "^11.0.0",
42 | "postcss-loader": "^2.0.8",
43 | "postcss-url": "^7.2.1",
44 | "rimraf": "^2.6.0",
45 | "semver": "^5.3.0",
46 | "shelljs": "^0.7.6",
47 | "uglifyjs-webpack-plugin": "^1.1.1",
48 | "url-loader": "^0.5.8",
49 | "vue-loader": "^13.3.0",
50 | "vue-style-loader": "^3.0.1",
51 | "vue-template-compiler": "^2.5.2",
52 | "webpack": "^3.6.0",
53 | "webpack-bundle-analyzer": "^2.9.0",
54 | "webpack-dev-server": "^2.9.1",
55 | "webpack-merge": "^4.1.0"
56 | },
57 | "engines": {
58 | "node": ">= 6.0.0",
59 | "npm": ">= 3.0.0"
60 | },
61 | "browserslist": [
62 | "> 1%",
63 | "last 2 versions",
64 | "not ie <= 8"
65 | ]
66 | }
67 |
--------------------------------------------------------------------------------
/server/index.js:
--------------------------------------------------------------------------------
1 | var ws = require("nodejs-websocket");
2 | var moment = require('moment');
3 |
4 | console.log("开始建立连接...")
5 |
6 | let users = [];
7 | let conns = {};
8 | let groups = [];
9 |
10 | function boardcast(obj) {
11 | if(obj.bridge && obj.bridge.length){
12 | obj.bridge.forEach(item=>{
13 | conns[item].sendText(JSON.stringify(obj));
14 | })
15 | return;
16 | }
17 | if (obj.groupId) {
18 | group = groups.filter(item=>{
19 | return item.id === obj.groupId
20 | })[0];
21 | group.users.forEach(item=>{
22 | conns[item.uid].sendText(JSON.stringify(obj));
23 | })
24 | return;
25 | }
26 |
27 | server.connections.forEach((conn, index) => {
28 | conn.sendText(JSON.stringify(obj));
29 | })
30 | }
31 |
32 | var server = ws.createServer(function(conn){
33 | conn.on("text", function (obj) {
34 | obj = JSON.parse(obj);
35 | conns[''+obj.uid+''] = conn;
36 | switch(obj.type){
37 | // 创建连接
38 | case 1:
39 | let isuser = users.some(item=>{
40 | return item.uid === obj.uid
41 | })
42 | if(!isuser){
43 | users.push({
44 | nickname: obj.nickname,
45 | uid: obj.uid,
46 | status: 1
47 | });
48 | } else {
49 | users.map((item, index)=>{
50 | if(item.uid === obj.uid){
51 | item.status = 1;
52 | }
53 | return item;
54 | })
55 | }
56 | boardcast({
57 | type: 1,
58 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
59 | msg: obj.nickname+'加入聊天室',
60 | users: users,
61 | groups: groups,
62 | uid: obj.uid,
63 | nickname: obj.nickname,
64 | bridge: obj.bridge
65 | });
66 | break;
67 | // 注销
68 | case 2:
69 | // delete conns[''+obj.uid+''];
70 | users.map((item, index)=>{
71 | if(item.uid === obj.uid){
72 | item.status = 0;
73 | }
74 | return item;
75 | })
76 | boardcast({
77 | type: 1,
78 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
79 | msg: obj.nickname+'退出了聊天室',
80 | users: users,
81 | groups: groups,
82 | uid: obj.uid,
83 | nickname: obj.nickname,
84 | bridge: []
85 | });
86 | break;
87 | // 创建群
88 | case 10:
89 | groups.push({
90 | id: moment().valueOf(),
91 | name: obj.groupName,
92 | users: [{
93 | uid: obj.uid,
94 | nickname: obj.nickname
95 | }]
96 | })
97 | boardcast({
98 | type: 1,
99 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
100 | msg: obj.nickname+'创建了群' + obj.groupName,
101 | users: users,
102 | groups: groups,
103 | uid: obj.uid,
104 | nickname: obj.nickname,
105 | bridge: obj.bridge
106 | });
107 | break;
108 | // 加入群
109 | case 20:
110 | let group = groups.filter(item=>{
111 | return item.id === obj.groupId
112 | })[0]
113 | group.users.push({
114 | uid: obj.uid,
115 | nickname: obj.nickname
116 | })
117 | boardcast({
118 | type: 1,
119 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
120 | msg: obj.nickname+'加入了群' + obj.groupName,
121 | users: users,
122 | groups: groups,
123 | uid: obj.uid,
124 | nickname: obj.nickname,
125 | bridge: obj.bridge
126 | });
127 | break;
128 | // 发送消息
129 | default:
130 | boardcast({
131 | type: 2,
132 | date: moment().format('YYYY-MM-DD HH:mm:ss'),
133 | msg: obj.msg,
134 | uid: obj.uid,
135 | nickname: obj.nickname,
136 | bridge: obj.bridge,
137 | groupId: obj.groupId,
138 | status: 1
139 | });
140 | break;
141 | }
142 | })
143 | conn.on("close", function (code, reason) {
144 | console.log("关闭连接")
145 | });
146 | conn.on("error", function (code, reason) {
147 | console.log("异常关闭")
148 | });
149 | }).listen(8001)
150 | console.log("WebSocket建立完毕")
--------------------------------------------------------------------------------
/src/App.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
11 |
12 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
30 |
31 |
32 | {{item.name}}
33 | {{item.unread}}
34 | +
35 |
36 |
37 | {{item.nickname}}
38 | {{item.unread}}
39 |
40 |
41 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | {{item.msg}}
55 |
56 |
57 |
58 | {{item.nickname}} {{item.date}}
59 | {{item.msg}}
60 |
61 |
62 |
63 |
64 |
68 |
69 |
70 |
71 |
72 |
73 |
303 |
304 |
307 |
--------------------------------------------------------------------------------
/src/app.styl:
--------------------------------------------------------------------------------
1 | $green = #00b7a3;
2 | *
3 | padding 0
4 | margin 0
5 | outline none
6 | button
7 | border none
8 | input
9 | border 1px solid #eee
10 | html, body, #app
11 | width 100%
12 | height 100%
13 | .nickname
14 | line-height 30px
15 | width 100%
16 | border 1px solid $green
17 |
18 | @-webkit-keyframes fColorAni{
19 | 0% {
20 | color: $green;
21 | }
22 | 50% {
23 | color: #46b0ff;
24 | }
25 | 100% {
26 | color: #333;
27 | }
28 | }
29 |
30 | .dis-flex
31 | display flex
32 | .web-im
33 | width 100%
34 | height 100%
35 | .content
36 | display: flex;
37 | flex-direction: row;
38 | flex: 1;
39 | box-sizing: border-box;
40 | min-width: 0;
41 | flex-direction: column;
42 | .header
43 | box-shadow 1px -1px 2px 2px #eee
44 | line-height 40px
45 | height 40px
46 | font-size 24px
47 | z-index 10
48 | background #fff
49 | .body
50 | flex 1
51 | overflow-y auto
52 | box-shadow 1px 1px 1px #eee
53 | .footer
54 | box-shadow 1px 1px 8px #eee
55 | height 60px
56 | .left
57 | width 220px
58 | .aside
59 | height 100%
60 | .tabbar
61 | label
62 | flex 1
63 | text-align center
64 | line-height 40px
65 | cursor pointer
66 | font-size 16px
67 | &.active
68 | color $green
69 | &:last-child
70 | border-left 1px solid #eee
71 | &.unread
72 | animation fColorAni .3s infinite
73 | .user-list
74 | top 0
75 | .func
76 | label
77 | flex 1
78 | text-align center
79 | line-height 60px
80 | cursor pointer
81 | &:last-child
82 | border-left 1px solid #eee
83 | .user
84 | line-height 40px
85 | padding 0 8px
86 | border-bottom 1px solid #eee
87 | &.offline
88 | color #ccc
89 | &.online
90 | color #333
91 | &.ani
92 | animation fColorAni .3s 5
93 | .tips-num
94 | height 18px
95 | font-size 12px
96 | color #ffffff
97 | background $green
98 | min-width 20px
99 | border-radius 50px
100 | display: inline-block;
101 | line-height: 18px;
102 | text-align center
103 | .add-group
104 | width 18px
105 | height 18px
106 | line-height 18px
107 | text-align center
108 | display inline-block
109 | border-radius 100%
110 | color $green
111 | border 1px solid $green
112 | cursor pointer
113 | .right
114 | flex 1
115 | .im-title
116 | padding-left 20px
117 | .body
118 | padding 10px 20px
119 | .im-record
120 | .join-tips
121 | position relative!important
122 | display block
123 | color #cccccc
124 | font-size 15px
125 | text-align center
126 | width 100%
127 | left 0!important
128 | transform none!important
129 | .li
130 | margin-bottom 15px
131 | position relative
132 | text-align left
133 | color #46b0ff
134 | &:after
135 | content ''
136 | display block
137 | clear both
138 | .message-date
139 | font-size 16px
140 | color #b9b8b8
141 | .m-nickname
142 | color #46b0ff
143 | &.user
144 | text-align right
145 | color $green
146 | .message-date
147 | .m-nickname
148 | color $green
149 | .message-box
150 | line-height 30px
151 | font-size 20px
152 | .footer
153 | input
154 | flex 1
155 | padding 0 20px
156 | font-size 24px
157 | button
158 | width 200px
159 | background $green
160 | color #fff
161 | font-size 24px
162 |
163 | //警告框
164 | div.my-el-message
165 | position absolute
166 | height 100%
167 | width 100%
168 | top 0
169 | left 0
170 | z-index 4000
171 | &.success .my-el-message__group
172 | background-image url('./assets/success.svg')
173 | .el-message-cover
174 | position fixed
175 | height 100%
176 | width 100%
177 | background #000
178 | opacity 0.2
179 | top 0
180 | left 0
181 | z-index 4001
182 | .my-el-message__group
183 | margin 0
184 | background #ffffff url('./assets/warn.svg') no-repeat 17px center
185 | background-size: 20px 20px
186 | top 50%
187 | border-radius 6px
188 | padding 0 40px 0 52px
189 | z-index 4002
190 | height 60px
191 | overflow hidden
192 | line-height 60px
193 | position fixed
194 | min-width 350px
195 | left 50%
196 | transform translateX(-50%)
197 | box-shadow 0 2px 8px rgba(0,0,0,.12), 0 0 6px rgba(0,0,0,.04)
198 | animation myshow .2s
199 |
200 | p
201 | margin 0
202 | color #333333
203 | font-size 14px
204 | padding-right 10px
205 | .my-el-message-close
206 | width 15px
207 | height 15px
208 | background url('./assets/close.svg') no-repeat
209 | background-size 15px 15px
210 | position absolute
211 | right 14px
212 | top 20px
213 | cursor pointer
214 | @keyframes myshow
215 | from
216 | transform scale(0) translateX(-100%)
217 | to
218 | transform scale(1) translateX(-50%)
219 |
220 |
221 | ::-webkit-scrollbar-thumb
222 | background-color: #ccc;
223 | height: 50px;
224 | outline-offset: -2px;
225 | outline: 2px solid #fff;
226 | -webkit-border-radius: 4px;
227 | border: 2px solid #fff;
228 |
229 | ::-webkit-scrollbar
230 | width: 8px;
231 | height: 8px;
--------------------------------------------------------------------------------
/src/assets/close.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/javanf/web-im/357b696cb89757b064115eabf7c2efe3e3edf711/src/assets/logo.png
--------------------------------------------------------------------------------
/src/assets/success.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/assets/warn.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/components/dialog/index.styl:
--------------------------------------------------------------------------------
1 | .popup
2 | width 100%
3 | height 100%
4 | background: rgba(0, 0, 0, 0.3)
5 | position fixed
6 | z-index 10000
7 | .dialog
8 | position relative
9 | width 500px
10 | height auto
11 | left 50%
12 | top 50%
13 | background #ffffff
14 | border-radius 5px
15 | transform translate(-50%, -50%)
16 | padding 20px
17 | box-shadow 2px 1px 1px #eee
18 | .title
19 | margin-bottom 20px
20 | .btn
21 | text-align center
22 | margin-top 20px
23 | button
24 | width 200px
25 | text-align center
26 | border none
27 | background #ccc
28 | line-height 40px
29 | cursor pointer
30 | &:last-child
31 | background #00b7a3
32 | color #fff
--------------------------------------------------------------------------------
/src/components/dialog/index.vue:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
16 |
54 |
55 |
--------------------------------------------------------------------------------
/src/components/message/index.js:
--------------------------------------------------------------------------------
1 | var option = {
2 | type: 'info', //主题,无用属性
3 | iconClass: '', //自定义图标类名,无用属性
4 | customClass: '', //自定义类名, 无用属性
5 | showClose: true, //是否显示关闭按钮,无用属性
6 | message: '', //消息文字
7 | duration: 2000, //显示时间,毫秒,为0提示框不关闭
8 | id: '', //消息id,动态时间戳
9 | onClose: null, //关闭之后的回调函数
10 | timer: 0
11 | };
12 | var Message = function(options, type) {
13 | if (typeof options === 'string') {
14 | option.message = options;
15 | } else {
16 | for (var i in options) {
17 | option[i] = options[i];
18 | }
19 | }
20 | (type) && (option.type = type);
21 | creatHtml();
22 | };
23 | var creatHtml = function() {
24 | var node = document.createElement("div");
25 | if (option.id) {
26 | document.getElementById(option.id + '-p').innerHTML = option.message;
27 | setTimeoutClose();
28 | return;
29 | }
30 | option.id = new Date().getTime();
31 | option.id = 'msg' + option.id;
32 | node.id = option.id;
33 | node.innerHTML = '' +
34 | option.message +
35 | '
';
36 | document.body.appendChild(node);
37 | bindClose();
38 | },
39 | bindClose = function() {
40 | document.getElementById(option.id + '-close').onclick = function() {
41 | close();
42 | };
43 | setTimeoutClose();
44 | },
45 | close = function() {
46 | var remove = document.getElementById(option.id);
47 | document.body.removeChild(remove);
48 | option.id = '';
49 | clearTimeout(option.timer);
50 | if (typeof option.onClose === 'function') {
51 | option.onClose(Message);
52 | }
53 | },
54 | setTimeoutClose = function() {
55 | clearTimeout(option.timer);
56 | if (option.duration > 0) {
57 | option.timer = setTimeout(function() {
58 | close();
59 | }, option.duration);
60 | }
61 | };
62 |
63 | ['success', 'warning', 'info', 'error'].forEach(function(type) {
64 | Message[type] = function(options) {
65 | return Message(options, type);
66 | };
67 | });
68 |
69 | export default Message;
--------------------------------------------------------------------------------
/src/main.js:
--------------------------------------------------------------------------------
1 | // The Vue build version to load with the `import` command
2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
3 | import Vue from 'vue'
4 | import App from './App'
5 | import router from './router'
6 |
7 | import messageUI from './components/message';
8 |
9 | Vue.config.productionTip = false
10 | Vue.prototype.$message = messageUI;
11 |
12 | /* eslint-disable no-new */
13 | new Vue({
14 | el: '#app',
15 | router,
16 | components: { App },
17 | template: ''
18 | })
19 |
--------------------------------------------------------------------------------
/src/router/index.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import Router from 'vue-router'
3 |
4 | Vue.use(Router)
5 |
6 | export default new Router({
7 | routes: [
8 | {
9 | path: '/',
10 | name: ''
11 | }
12 | ]
13 | })
14 |
--------------------------------------------------------------------------------
/static/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/javanf/web-im/357b696cb89757b064115eabf7c2efe3e3edf711/static/.gitkeep
--------------------------------------------------------------------------------