本文介绍websocket实现前端通讯
要实现通讯需要连接、发送、接收以及需要websocket服务器
我们来看一个简单的websocket demo
var socket = new WebSocket('ws://localhost:8080/');
socket.onopen = function () {
console.log('Connected!');
};
socket.onmessage = function (event) {
console.log('Received data: ' + event.data);
socket.close();
};
socket.onclose = function () {
console.log('Lost connection!');
};
socket.onerror = function () {
console.log('Error!');
};
socket.send('hello, world!');
可以说上面就是一个健全的websocket 通信了. 我们需要创建一个WebSocket对象, 里面的参数指定连接的路由. 而且,他也是事件驱动的.常见的事件监听有.
event | effect |
---|---|
open | 当ws连接建立时触发 |
message | 当有信息到来时触发 |
error | 当连接发生错误时触发 |
close | 当连接断开时触发 |
websocket 发送数据
另外,websocket 最大的特点就是可以双向通信。这里可以使用.ws.send()
方法发送数据, 不过只能发送String和二进制. 这里,我们通常call 数据叫做 Frames
. 他是数据发送的最小单元.包含数据的长度和数据内容.下面就是几种常用的发送方式
socket.send("Hello server!");
socket.send(JSON.stringify({'msg': 'payload'}));
var buffer = new ArrayBuffer(128);
socket.send(buffer);
var intview = new Uint32Array(buffer);
socket.send(intview);
var blob = new Blob([buffer]);
socket.send(blob);
另外还可以使用binaryType指定传输的数据格式,不过一般都用不上,就不说了.不过需要提醒的是, send方法,一般在open和message的回调函数中调用.
websocket 接受数据
同理,和SSE差不多, 通过监听message事件,来接受server发送回来的数据. 接受其实就是通过event.data
来获取. 不过, 需要和server端商量好data的类型.
ws.onmessage = function(msg) {
if(msg.data instanceof Blob) {
processBlob(msg.data);
} else {
processText(JSON.parse(msg.data)); //接受JSON数据
}
}
那server端应该怎样处理websocket通信呢? websocket虽然是另外一种协议,不过底层还是封装了TCP通信, 所以使用nodeJS的net模块,基本就可以满足,不过里面需要设置很多的头. 这里推荐使用ws模块.
NodeJS 发送websocket数据
简单的websocket demo
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 8080 });
//通过ws+ssl的方式通信. 和HTTPS类似
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
具体代码示例:
html
<div id="page-wrapper">
<h1>WebSockets Demo</h1>
<div id="status">Connecting...</div>
<ul id="messages"></ul>
<form id="message-form" action="#" method="post">
<textarea id="message" placeholder="Write your message here..." required></textarea>
<button type="submit">Send Message</button>
<button type="button" id="close">Close Connection</button>
</form>
</div>
css
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 100%;
background: #333;
}
#page-wrapper {
width: 650px;
background: #FFF;
padding: 1em;
margin: 1em auto;
border-top: 5px solid #69c773;
box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}
h1 {
margin-top: 0;
}
#status {
font-size: 0.9rem;
margin-bottom: 1rem;
}
.open {
color: green;
}
.closed {
color: red;
}
ul {
list-style: none;
margin: 0;
padding: 0;
font-size: 0.95rem;
}
ul li {
padding: 0.5rem 0.75rem;
border-bottom: 1px solid #EEE;
}
ul li:first-child {
border-top: 1px solid #EEE;
}
ul li span {
display: inline-block;
width: 90px;
font-weight: bold;
color: #999;
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 1px;
}
.sent {
background-color: #F7F7F7;
}
.received {}
#message-form {
margin-top: 1.5rem;
}
textarea {
width: 100%;
padding: 0.5rem;
font-size: 1rem;
border: 1px solid #D9D9D9;
border-radius: 3px;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
min-height: 100px;
margin-bottom: 1rem;
}
button {
display: inline-block;
border-radius: 3px;
border: none;
font-size: 0.9rem;
padding: 0.6rem 1em;
color: white;
margin: 0 0.25rem;
text-align: center;
background: #BABABA;
border-bottom: 1px solid #999;
}
button[type="submit"] {
background: #86b32d;
border-bottom: 1px solid #5d7d1f;
}
button:hover {
opacity: 0.75;
cursor: pointer;
}
JS
window.onload = function() {
// Get references to elements on the page.
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
// Create a new WebSocket.
var socket = new WebSocket('ws://echo.websocket.org');
// Handle any errors that occur.
socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
// Show a connected message when the WebSocket is opened.
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ws://echo.websocket.org';
socketStatus.className = 'open';
};
// Handle messages sent by the server.
socket.onmessage = function(event) {
var message = event.data;
messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
message + '</li>';
};
// Show a disconnected message when the WebSocket is closed.
socket.onclose = function(event) {
socketStatus.innerHTML = 'Disconnected from WebSocket.';
socketStatus.className = 'closed';
};
// Send a message when the form is submitted.
form.onsubmit = function(e) {
e.preventDefault();
// Retrieve the message from the textarea.
var message = messageField.value;
// Send the message through the WebSocket.
socket.send(message);
// Add the message to the messages list.
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
'</li>';
// Clear out the message field.
messageField.value = '';
return false;
};
// Close the WebSocket connection when the close button is clicked.
closeBtn.onclick = function(e) {
e.preventDefault();
// Close the WebSocket.
socket.close();
return false;
};
};
欢迎加qq群交流:610334712
websocket知识:xxxx连接
nodejs服务端信息:xxxx连接
参考及更多ajax、JSOP、SSE实现前端通讯请阅读
https://segmentfault.com/a/1190000004682473#articleHeader8