var exampleSocket = newWebSocket("ws://www.example.com/socketserver");
Web Sockets 的方法
方法名称
参数
描述
send(data)
data表示发送的请求数据。
通过 WebSocket 连接向服务器发送数据。
close()
关闭WebSocket连接或停止正在进行的连接请求。
1
exampleSocket.send("Here's some text that the server is urgently awaiting!");
Web Sockets 的属性
Web Sockets 的属性主要使用的就是 readyState,该属性表示连接的当前状态。
常量名
值
描述
CONNECTING
0
连接还没开启。
OPEN
1
连接已开启并准备好进行通信。
CLOSING
2
连接正在关闭的过程中。
CLOSED
3
连接已经关闭,或者连接无法建立。
Web Sockets 的事件
事件名称
描述
onopen
用于监听 Web Sockets 打开的事件。
onmessage
用于监听 Web Sockets 服务器端传递消息的事件。
onerror
用于监听 Web Sockets 发生错误的事件。
onclose
用于监听 Web Sockets 通信关闭的事件。
Web Sockets 使用步骤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var ws = newWebSocket('ws://127.0.0.1:8080/async'); ws.onopen = function() { // called when connection is opened }; ws.onerror = function(e) { // called in case of error, when connection is broken in example }; ws.onclose = function() { // called when connexion is closed }; ws.onmessage = function(msg) { // called when the server sends a message to the client. // msg.data contains the message. }; // Here is how to send some data to the server ws.send('some data'); // To close the socket: ws.close();