- Notifications
You must be signed in to change notification settings - Fork35
jaywcjlove/websocket
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
ws 对象提供了建立、管理 WebSocket 服务器的握手连接的 API,它也有在连接中传送、接收数据的能力。
# bower 下载bower install websocket# npm 下载npm install websocketjs进入websocket 根目录 在命令行中运行grunt 会输出下面内容,127.0.0.1:8080 是打开index.html 页面,ws://127.0.0.1:3001
同时自动压缩websocket.js
--WebSocket-------------WebSocket address: ws://127.0.0.1:3001WebSocket has started.--Server----------------Server address: http://127.0.0.1:8080Server running... press ctrl-c to stop.Server has started.------------------------将原生websocket调用socket = new WebSocket(url,protocol) 更换成socket = new ws(url,protocol)
varsocket,url='ws://127.0.0.1:3001';//原生websocket使用换成下面 ws 方法socket=newWebSocket(url);//换成了ws 方法之后,下面的事件才有作用socket=newws(url);
readyState 属性使用以下常数描述WebSocket 的连线状态。
socket.readyState//=>1
| 常数 | 值 | 描述 |
|---|---|---|
| CONNECTING | 0 | 连接尚未打开。 |
| OPEN | 1 | 连接已打开,可以进行通讯。 |
| CLOSING | 2 | 连接正在进行关闭程序。 |
| CLOSED | 3 | 连接已关闭/连接不能打开。 |
连接成功会执行这个事件
接收websocket推送过来的消息
这是个监听事件,当连接开始尝试进行,事件监听器被调用。
websocket关闭会执行这个事件
通过websocket向后端发送消息。
关闭 WebSocket 连接/连接尝试,若连接已为 CLOSED,此方法沒有作用。
socket.close(1000,'kiki');
表示状态码,状态代码用以解释连接关闭的原因。弱未指定参数,预设值为1000(表示正常的「事物完结 transaction complete 」关闭),参考CloseEvent 页面的状态码列表,有所有的合法状态码值。
解释连接断开的原因人类可读字符串,字符串不可大于 123 个 UTF-8 字符串
varsocket=newws('ws://127.0.0.1:3001'),str="JSLite.io";socket.onconnecting=function(evn){console.log("socket:onconnecting:",evn);// sendMsg("wcj");}socket.onopen=function(evn){console.log("socket:onopen:",evn);log('发了个消息!"'+str+'"');sendMsg(str);}socket.onclose=function(evn){console.log("socket.onclose:",evn);log('WebSocket 被你关闭了!,您老人家再也没有办法建立连接了?');}socket.onmessage=function(evn){console.log("socket:onmessage:",evn);log('收到消息!"'+evn.data+'"');// socket.close()}functionsendMsg(str){console.log("socket:sendMsg:",socket);socket.send(str);}
npm start
About
websocket APIs 简单封装,还赠送一个nodejs搭建websocket服务实例
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.