开发者

HTML5 opening two web sockets from one html page

开发者 https://www.devze.com 2023-03-30 02:19 出处:网络
Can I open two WebSocket connections to one server but two different ports from one html page. I\'ve searched in google but couldn\'t find anything useful. And also can you give me links to some tuto

Can I open two WebSocket connections to one server but two different ports from one html page.

I've searched in google but couldn't find anything useful. And also can you give me links to some tutorials for web sockets. These are the ones i found:

http://websocket.org/echo.html

http://www.html5rocks.com/en/tutorials/webs开发者_开发问答ockets/basics/


Would this not work?

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

As for how your server handles it, it would very much depend on your server side technology.

For tutorials, the client-side aspect of WebSockets is dead easy, this is pretty much it:

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');
}

The server-side aspect of how to handle incoming WebSocket connections is a lot more complex, and varies depending on your server-side technology (ASP.NET, PHP, Node.js etc.).

0

精彩评论

暂无评论...
验证码 换一张
取 消