WebSocket


WebSocket API:允许客户端代码在客户端和支持 WebSocket 协议的服务器端创建双向的套接字类型的连接。使用非常简单,首先,通过 WebSocket() 构造函数创建套接字:

var socket = new WebSocket("ws://ws.example.com:1234/resource");

创建了套接字之后,通常需要在上面注册一个事件处理程序:

socket.onopen = function(e) {/* 套接字已经连接 */};
socket.onclose = function(e) {/* 套接字已经关闭 */};
socket.onerror = function(e) {/* 出错了 */};
socket.onmessage = function(e) {/* 消息处理 */};  

为了通过套接字发送数据给服务器,可以调用套接字的 send() 方法:

socket.send("Hello, server!");

完成客户端与服务器的通信之后,可以通过 close() 方法关闭 WebSocket。通过 WebSocket 来实现在线聊天室非常简单:

客户端代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Chat Client</title>
    </head>
    <body>
        <script>
            window.onload = function () {
                var nick = prompt("Enter your nickname");
                var input = document.getElementById("input");
                input.focus();
            
                var socket = new WebSocket("ws://" + location.host + "/");
            
                socket.onmessage = function (event) {
                    var msg = event.data;
                    var node = document.createTextNode(msg);
                    var div = document.createElement("div");
                    div.appendChild(node);
                    document.body.insertBefore(div, input);
                    input.scrollIntoView();
                };
            
                input.onchange = function () {
                    var msg = nick + ": " + input.value;
                    socket.send(msg);
                    input.value = "";
                };
            }
        </script>
        <input id="input" style="width: 100%;">
    </body>
</html>

服务端代码:

var http = require("http");
var ws = require("websocket-server");
    
var clientui = require("fs").readFileSync("client.html");
    
var httpserver = new http.Server();
    
httpserver.on("request", function (request, response) {
    if (request.url === '/') {
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write(clientui);
        response.end();
    } else {
        response.writeHead(404);
        response.end();
    }
});
    
// 在 HTTP 服务器上包装一个 WebSocket 服务器
var wsserver = ws.createServer({server: httpserver});
    
wsserver.on("connection", function (socket) {
    socket.send("Welcome to the chat room");
    socket.on("message", function (msg) {   // 监听来自客户端的消息
        wsserver.broadcast(msg);     // 将消息广播出去
    });
});
    
// 在 8000 端口运行 WebSocket 服务器,启动它的同时也会启动 HTTP 服务器
wsserver.listen(8000);

Vote Vote Cancel Collect Collect Cancel

<< 上一篇: 文件系统与客户端数据库

>> 下一篇: 没有下一篇了