javascript 客户端webSocket示例


 1 //html
 2 
 3 <script>
 4 // 初始化一个 WebSocket 对象
 5 var ws = new WebSocket("ws://localhost:9998/echo");
 6 
 7 // 建立 web socket 连接成功触发事件
 8 ws.onopen = function () {
 9   // 使用 send() 方法发送数据
10   ws.send("发送数据");
11   alert("数据发送中...");
12 };
13 
14 // 接收服务端数据时触发事件
15 ws.onmessage = function (evt) {
16   var received_msg = evt.data;
17   alert("数据已接收...");
18 };
19 
20 // 断开 web socket 连接成功触发事件
21 ws.onclose = function () {
22   alert("连接已关闭...");
23 };
24 </script>


 1 var wsServer = 'ws://localhost:8888/Demo'; //服务器地址 "ws://IP:端口"
 2 var websocket = new WebSocket(wsServer); //创建WebSocket对象
 3 websocket.send("hello");//向服务器发送消息
 4 alert(websocket.readyState);//查看websocket当前状态
 5 websocket.onopen = function (evt) {
 6 //已经建立连接
 7 };
 8 websocket.onclose = function (evt) {
 9 //已经关闭连接
10 };
11 websocket.onmessage = function (evt) {
12 //收到服务器消息,使用evt.data提取
13 };
14 websocket.onerror = function (evt) {
15 //产生异常
16 }; 
原文地址:https://www.cnblogs.com/weihexinCode/p/12317599.html