WebSocket JavaScript 接口定义:
简单了解下接口方法和属性:
- [Constructor(in DOMString url, optional in DOMString protocol)]
- interface WebSocket {
- readonly attribute DOMString URL;
- // ready state
- const unsigned short CONNECTING = 0;
- const unsigned short OPEN = 1;
- const unsigned short CLOSED = 2;
- readonly attribute unsigned short readyState;
- readonly attribute unsigned long bufferedAmount;
- // networking
- attribute Function onopen;
- attribute Function onmessage;
- attribute Function onclose;
- boolean send(in DOMString data);
- void close();
- };
- WebSocket implements EventTarget;
JavaScript调用浏览器接口实例如下:
- var wsServer = 'ws://localhost:8888/Demo'; //服务器地址
- var websocket = new WebSocket(wsServer); //创建WebSocket对象
- websocket.send("hello");//向服务器发送消息
- alert(websocket.readyState);//查看websocket当前状态
- websocket.onopen = function (evt) {
- //已经建立连接
- };
- websocket.onclose = function (evt) {
- //已经关闭连接
- };
- websocket.onmessage = function (evt) {
- //收到服务器消息,使用evt.data提取
- };
- websocket.onerror = function (evt) {
- //产生异常
- };