要创建 Web Socket,先实例一个 WebSocket 对象并传入要连接的 URL:
var socket = new WebSocket("ws://localhost:1234/");
创建Web Sockets 前可以先检验一下浏览器是否支持该API:
if (window.WebSocket) {
console.log('This browser supports WebSocket');
} else {
console.log('This browser does not supports WebSocket');
}
- 发送和接收数据
Web Socket 打开之后,就可以通过连接发送和接收数据。要向服务器发送数据,使用 send()方法并传入任意字符串,例如:
var socket = new WebSocket("ws://localhost:1234/");
socket.send("Hello world!");
因为 Web Sockets 只能通过连接发送纯文本数据,所以对于复杂的数据结构,在通过连接发送之前,必须进行序列化。下面的例子展示了先将数据序列化为一个 JSON 字符串,然后再发送到服务器:
var message = {
time: new Date(),
text: "Hello world!",
};
socket.send(JSON.stringify(message));
WebSocket 对象还有其他三个事件,在连接生命周期的不同阶段触发。
open:在成功建立连接时触发。
error:在发生错误时触发,连接不能持续。
close:在连接关闭时触发。
举个简单的例子
前端页面:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<title>websocket test</title>
<script>
var socket;
if(window.WebSocket){
console.log('This browser supports WebSocket');
}else{
console.log('This browser does not supports WebSocket');
}
function Connect(){
socket=new WebSocket('ws://localhost:1234/');
socket.onopen = sOpen;
socket.onerror = sError;
socket.onmessage= sMessage;// 监听服务端发送的数据
socket.onclose= sClose;
}
function sOpen(){
console.log('connect success!');
}
function sError(e){
console.log("error " + e);
}
function sMessage(msg){
console.log( msg);
var msg1 = JSON.parse(msg.data);
var dom = document.createElement('div');
dom.innerHTML = 'server say:'+ msg1.text;
$('message')[0].appendChild(dom);
}
function sClose(e){
console.log("connect closed:" + e.code);
}
function Send(){
var message = {
time: new Date(),
text: document.getElementById("msg").value,
};
socket.send(JSON.stringify(message));
var dom = document.createElement('div');
dom.innerHTML = 'I say:'+document.getElementById("msg").value;
$('message')[0].appendChild(dom);
}
function Close(){
socket.close();
}
function $(name){
return document.getElementsByClassName(name);
}
</script>
</head>
<body>
<input id="msg" type="text">
<button id="connect" onclick="Connect();">Connect</button>
<button id="send" onclick="Send();">Send</button>
<button id="close" onclick="Close();">Close</button>
<div class="message"></div>
</body>
</html>
服务端代码(nodejs实现):
// 注:该js 文件与上部分html在同一级目录
const http = require('http');
const fs = require('fs');
const url = require('url');
const express = require('express');
const path = require('path');
const SocketServer = require('ws').Server;
const app = express();
app.use(express.static(path.join(__dirname, '/')));
const PORT = '1234';
let server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const ws = new SocketServer({ server });
ws.on('connection', function (connection) {
connection.on('message', function (message) {
let myMessage = JSON.parse(message);
// 接收到客户端发送的数据后,发送数据给客户端
connection.send(JSON.stringify(myMessage));
})
});