我可以从一个html页面打开到一台服务器的两个WebSocket连接,但打开两个不同的端口。

我在Google中搜索过,但找不到任何有用的信息。另外,您还可以给我一些Web套接字教程的链接。这些是我发现的:

http://websocket.org/echo.html

http://www.html5rocks.com/en/tutorials/websockets/basics/

最佳答案

这行不通吗?

var socket1 = new WebSocket('ws://localhost:1001');
var socket2 = new WebSocket('ws://localhost:1002');

至于服务器的处理方式,则在很大程度上取决于服务器端技术。

对于教程,WebSockets的客户端方面非常简单,这几乎就是:
var socket;

// Firefox uses a vendor prefix
if (typeof(MozWebSocket) != 'undefined') {
    socket = new MozWebSocket('ws://localhost');
}
else if (typeof(WebSocket) != 'undefined') {
    socket = new WebSocket('ws://localhost');
}

if (socket != null) {
    socket.onmessage = function(event) {
        // fired when a message is received from the server
        alert(event.data);
    };

    socket.onclose = function() {
        // fired when the socket gets closed
    };

    socket.onerror = function(event) {
        // fired when there's been a socket error
    };

    socket.onopen = function() {
        // fired when a socket connection is established with the server,
        // Note: we can now send messages at this point

        // sending a simple string to the server
        socket.send('Hello world');

        // sending a more complex object to the server
        var command = {
            action: 'Message',
            time: new Date().toString(),
            message: 'Hello world'
        };
        socket.send(JSON.stringify(command));
    };
}
else {
    alert('WebSockets are not supported by your browser');
}

服务器端方面如何处理传入的WebSocket连接要复杂得多,并且取决于您的服务器端技术(ASP.NET,PHP,Node.js等)。

07-24 09:51
查看更多