WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议,其优雅地解决了以往web服务器不能向web客户端实时推送消息的问题。
在浏览器js环境中,创建一个websocket对象如下所示:
var ws = New WebSocket(url, [protocol])
第一个参数 url, 指定连接的 URL,一般web服务器会对这个url进行特殊的处理,一般会用实现了websocket协议的handler处理websocket请求。
第二个参数 protocol 是可选的,指定了可接受的子协议。
WebSocket事件
websocket提供了四个回调函数,分别用来处理open,close,message,error四个事件,即ws.onopen,ws.onclose,ws.onmessage,ws.onerror
举个栗子:
var ws_req = {
socket: null,
start: function() {
var Is_Flash_running = false;
var total_fail_count = 0;
if ("WebSocket" in window) {
var url = "ws://" + location.host + "/socket_req";
if (ws_req.socket){
ws_req.socket.close();
}
ws_req.socket = new WebSocket(url);
ws_req.socket.onopen = function() {
console.log("Opening a connection...");
ws_req.socket.send("connect to web server......")
};
ws_req.socket.onclose = function(evt) {
console.log("I'm sorry. Bye!");
};
ws_req.socket.onerror = function(evt) {
console.log("ERR: " + evt.data);
};
ws_req.socket.onmessage = function(event) {
try {
handleMessage(event.data);
} catch (err) {
console.log(err);
}
}
} else {
alert('你的浏览器太落伍了,换用高版本的chrome内核浏览器吧!!!');
}
},
}
ws_req.start();
var handleMessage = function(data){
//
}
web服务器实现:
笔者使用的后端开发语言是python,用的是Tornado web框架,tornado.websocket已经封装了websocket的协议,我们仅需简单的调用即可
import tornado.web
import tornado.websocket
import traceback from device_serial_load import DevSerialLoadHandler class LoadDevSerialSocketHandler(tornado.websocket.WebSocketHandler):
client = set() def get_compression_options(self):
# Non-None enables compression with default options.
return {} def open(self):
LoadDevSerialSocketHandler.client.add(self) def on_close(self):
LoadDevSerialSocketHandler.client.remove(self)
try:
self.dslhler.dev_serial_load_client.stop()
except Exception, e:
logger.info('close socket client') def send_msg_to_broswer(self, msg):
try:
self.write_message(msg)
return True
except:
logger.error(str(msg) + '发送失败')
self.close()
return False def on_message(self, message):
message_json = json.loads(message)
if "NodeID" in message_json and "LineNum" in message_json :
node_ip = TestNodeData().get_node_ip(message_json["NodeID"])
line_num = message_json["LineNum"][2]
self.dslhler = DevSerialLoadHandler(node_ip, line_num, self.send_msg_to_broswer)
self.dslhler.start()
elif "InputMessage" in message_json:
try:
if message_json["InputMessage"] == "None":
# 支持网页仅回车键的发送
self.dslhler.dev_serial_load_client.client.send(" ")
else:
self.dslhler.dev_serial_load_client.client.send(message_json["InputMessage"])
except Exception, e:
logger.error(e)
logger.error(traceback.format_exc())
logger.error("send input message to dev serial fail")
self.send_msg_to_broswer("<span style='color:red;font-size:20px'>ATCServer:[串口命令发送失败]</span>\r\n")
上诉代码将串口打印通过websocket实时的传输到web页面显示