案例

var socket;
function connect() {
  var host = "ws://" + $("serverIP").value + ":" + $("serverPort").value + "/";
  socket = new WebSocket(host);
  try {
    socket.onopen = function (msg) {
      $("btnConnect").disabled = true;
      alert("连接成功!");
    };

    socket.onmessage = function (msg) {
      if (typeof msg.data == "string") {
        displayContent(msg.data);
      } else {
        alert("非文本消息");
      }
    };
    //关闭回调
    socket.onclose = function (msg) {
      alert("socket closed!");
    };
  } catch (ex) {
    log(ex);
  }
}

function send() {
  var msg = $("sendText").value + "\0";
  socket.send(msg);
}

window.onbeforeunload = function () {
  try {
    //关闭通信
    socket.close();
    socket = null;
  } catch (ex) {}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38