https://github.com/yezihaohao/notification
notification with socket.io
https://github.com/yezihaohao/notification
front-end javascript nodejs notification socket-io
Last synced: 8 months ago
JSON representation
notification with socket.io
- Host: GitHub
- URL: https://github.com/yezihaohao/notification
- Owner: yezihaohao
- Created: 2017-02-19T10:55:17.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-06-08T07:14:01.000Z (about 9 years ago)
- Last Synced: 2025-04-05T12:42:03.524Z (about 1 year ago)
- Topics: front-end, javascript, nodejs, notification, socket-io
- Language: HTML
- Size: 20.5 KB
- Stars: 25
- Watchers: 0
- Forks: 10
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
### notification
notification with socket.io
#### 1
npm install
#### 2
node index.js
#### 3
open the browser and visit http://localhost:8080/
### 前言
> socket.io: 包含对websocket的封装,可实现服务端和客户端之前的通信。详情见[官网](http://socket.io) (虽然是英文文档,但还是通俗易懂)。
Notification: Html5新特性,用于浏览器的桌面通知,只有部分浏览器支持。
通过nodejs+Socket.io+Notification实现服务端往浏览器客户端发送自定义消息。
若有问题可加群264591039与我讨论。
转载请注明出处!
### 开发前提
本地安装nodejs以及npm
对nodejs以及express框架有一定了解。(本篇将和官方文档一样,采用express 4.10.2)
### 环境搭建
- 新建一个文件夹notification(以下操作都在该文件夹的根目录进行)
- npm初始化package.json文件 `npm init`
- 安装express(指定版本4.10.2,没有试过其他版本,感兴趣可以试下) `npm install --save express@4.10.2`
- 安装socket.io(本人安装的版本是1.7.3) `npm install --save socket.io`
### 编写代码
#### 构建通信环境
在根目录下新建一个index.html(注:index页面的样式来自socket.io的官方示例)
```
Socket.IO Notification
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
Send
```
新建一个index.js文件,并在js文件中构建相应的对象和变量,创建监听端口为8080 的服务器,以及添加映射到index.html的路由。
```bash
let express = require('express'),
app = express(),
http = require('http').Server(app),
io = require('socket.io')(http);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(8080, function(){
console.log('listening on port 8080');
});
```
运行 `node index.js` 用浏览器打开http://localhost:8080 成功的话即可看到index.html页面的内容。
在index.js的监听端口代码上方添加socket.io的监听事件,监听用户连接的connection。
```bash
io.on('connection', function(socket){
console.log('a user connected');
});
```
创建监听Event事件:notification,并用emit向客户端推送消息
```bash
io.on('connection', function(socket){
console.log('a user connected');
socket.on('notification', function(msg){
console.log(msg);
io.emit('notification', msg);
});
});
```
在index.html页面中的