webSocket基本使用
websocket 协议: 服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话
一.原生JS使用webSocket客户端
// 1.0 连接地址为:"wss://echo.websocket.org"的服务器
var ws = new WebSocket("wss://echo.websocket.org")
// 2.0 连接成功的回调函数
ws.onopen = function (evt) {
console.log('客户端与服务器建立连接成功')
// 3.0 发送消息到服务器
ws.send('Hello WebSocket')
}
// 4.0 接收消息
ws.onmessage = function (evt) {
console.log('客户接收到的消息为:' + evt.data)
// 5.0 关闭连接
ws.close()
}
// 6.0 设置关闭的事件
ws.onclose = function () {
console.log('客户端与服务器连接关闭')
}
二.Vue使用webSocket的客户端
github地址: https://github.com/socketio/socket.io
下载: npm i socket.io-client --save
使用:
// 导入
import io from 'socket.io-client'
export default {
mounted () {
// 创建与服务器的连接(地址和token为示例)
var socket = io('http://ttapi.research.itcast.cn?token=' + this.$store.state.userInfo.token)
// 发送数据(参数为示例,这里的参数是对象)
socket.emit('message', {
msg: '发送数据',
timestamp: Date.now()
})
// 接收服务器返回消息的监听事件
socket.on('message', res => {
console.log(res)
})
}
}
三.Node使用webSocket服务端
官网示例: https://socket.io/get-started/chat/
服务端:
var app = require('express')()
var http = require('http').createServer(app)
var io = require('socket.io')(http)
app.get('/', function (req, res) {
// 根据实际而定
res.sendFile(__dirname + '/views/index.html')
})
// 接收客户端的信息
// 方法中socket是连接当前服务器的那个socket对象
io.on('connection', function (socket) {
socket.on('chat message', function (msg) {
console.log('接收的信息为: ' + msg);
// 向客户端返回消息
socket.emit('chat message', msg)
});
});
http.listen(3000, function () {
console.log('开启服务器');
})
客户端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* { 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: 0.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; }
</style>
</head>
<body>
<div>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</div>
</body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
// 客户端向服务器发送消息
$(function () {
var socket = io();
$('form').submit(function (e) {
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
})
// 接收服务端返回的消息
socket.on('chat message', msg => {
var li = $('<li>')
li.text(msg)
$('#messages').append(li)
})
});
</script>
</html>
示例说明:
一. 开启node文件的服务器 node .\App.js
二. 登录该服务器地址
三. 客户端在聊天框中输入内容
四. 发送内容到服务端
五. 服务端接收消息
六. 服务端向客户端返回消息
七. 客户端接收服务端返回的消息
九. 将返回的消息渲染到页面