Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

websocket APIs 简单封装,还赠送一个nodejs搭建websocket服务实例

NotificationsYou must be signed in to change notification settings

jaywcjlove/websocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GitHub issuesGitHub forksGitHub stars

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

readyState 属性使用以下常数描述WebSocket 的连线状态。

socket.readyState//=>1
常数描述
CONNECTING0连接尚未打开。
OPEN1连接已打开,可以进行通讯。
CLOSING2连接正在进行关闭程序。
CLOSED3连接已关闭/连接不能打开。

onopen

连接成功会执行这个事件

onmessage

接收websocket推送过来的消息

onconnecting

这是个监听事件,当连接开始尝试进行,事件监听器被调用。

onclose

websocket关闭会执行这个事件

send

通过websocket向后端发送消息。

close

关闭 WebSocket 连接/连接尝试,若连接已为 CLOSED,此方法沒有作用。

socket.close(1000,'kiki');

code 可选

表示状态码,状态代码用以解释连接关闭的原因。弱未指定参数,预设值为1000(表示正常的「事物完结 transaction complete 」关闭),参考CloseEvent 页面的状态码列表,有所有的合法状态码值。

reason 可选

解释连接断开的原因人类可读字符串,字符串不可大于 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

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp