【问题标题】:HTML5 opening two web sockets from one html pageHTML5 从一个 html 页面打开两个 Web 套接字
【发布时间】:2011-11-02 14:58:58
【问题描述】:

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

我在谷歌上搜索过,但找不到任何有用的东西。您还可以给我一些 Web 套接字教程的链接吗?这些是我找到的:

http://websocket.org/echo.html

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

【问题讨论】:

    标签: javascript html websocket


    【解决方案1】:

    这样不行吗?

    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 等)。

    【讨论】:

    • 我一直在尝试实现 Websockets,但问题是我们的生产服务器非常安全,即使安装了 node.js 或 socket.io 等服务,是否有纯 php5 实现或只是 javascript,我们可以只将项目上传到网络服务器,一切正常,无需安装或配置。可能吗?我们使用 cakePHP 2.3 作为我们的 php 框架
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    相关资源
    最近更新 更多