Skip to content

Instantly share code, notes, and snippets.

@curder
Last active December 10, 2017 14:18
Show Gist options
  • Save curder/ac43537b0cc0bc676b5ec8aee75159b1 to your computer and use it in GitHub Desktop.
Save curder/ac43537b0cc0bc676b5ec8aee75159b1 to your computer and use it in GitHub Desktop.
socketIO初探,简单的实现客户端和服务端事件的推送
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat Demo</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="m in messages" v-text="m"></li>
</ul>
<form @submit.prevent="send()">
<input type="text" id="chat" v-model="message">
<button>发送</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
var socket = io();
new Vue({
el:"#app",
data: {
messages: [],
message: ''
},
mounted() {
// 监听信息额更新,如有更新就放入messages变量中
socket.on('chat.message', function(message) {
this.message = ''
this.messages.push(message)
}.bind(this));
// 监听用户断开连接
socket.on('disconnected', function(message) {
socket.emit('chat.message', message);
});
},
methods: {
send() {
// 通知node服务端
socket.emit('chat.message', this.message)
}
}
});
</script>
</body>
</html>
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000); // 监听本地 3000端口
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html') // 渲染停同级目录下的index.html页面
})
// 客户端连接事件
io.on('connection', function(socket) {
// 监听客户端事件
socket.on('chat.message', function(message){
// 通知客户端处理事件
io.emit('chat.message', message);
});
// 监听客户端断开连接,并调用事件处理
socket.on('disconnect', function(){
// 通知客户端处理事件
io.emit('chat.message', '用户断开连接了');
});
})
{
"dependencies": {
"express": "^4.16.2",
"socket.io": "^2.0.4"
}
}
@curder
Copy link
Author

curder commented Dec 10, 2017

以上3个文件在同一目录下,运行npm install 安装更新依赖,nodeJS监听的是本地3000端口,可以在浏览器中打开http://localhost:3000访问效果。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment