首页 > 代码库 > WebSocket 相关知识

WebSocket 相关知识

检测浏览器是否支持WebSocket

var WebSocketsExist = true;
            try {
                var dummy = new WebSocket("ws://localhost:8989/test");
            } catch (ex) {
                try
                {
                    webSocket = new MozWebSocket("ws://localhost:8989/test");
                }
                catch(ex)
                {
                    WebSocketsExist = false;
                }
            }

            if (WebSocketsExist) {
                // 支持
            } else {
                // 不支持
            }

第二种检测WebSocket支持情况的写法:

function IstSupportWebSocket() {
    if (window.WebSocket) {
        //supported
    } else {
        // not supported
    }
}

ws:// --- WebSocket连接

wss:// --- 安全的WebSocket连接

创建对象、连接服务器

url = "ws://localhost:8080/echo";

w = new WebSocket(url);