iOS上的WebSockets

时间:2011-04-07 00:00:51

标签: iphone ios ipad websocket

我读过WebSockets适用于iOS 4.2及更高版本。我可以验证确实存在WebSocket对象。但我找不到一个可在手机上运行的WebSocket示例。

例如http://yaws.hyber.org/websockets_example.yaws会使Mobile Safari应用程序崩溃。有没有人让WebSockets在手机上成功运作?

6 个答案:

答案 0 :(得分:11)

我可能已经找到了解决方案。当您通过wifi设置代理时,Mobile Safari仅与websockets崩溃。

答案 1 :(得分:6)

支持,但请记住iOS Safari浏览器实现的标准,它不是RFC 6455,而是HyBi-00 / Hixie-76。

您也可以使用此浏览器进行测试:http://websocketstest.com/

同时查看这篇包含大部分版本信息的帖子:https://stackoverflow.com/a/2700609/1312722


OBS!,这是一个老答案。 我已经查看了这篇文章中提到的与browserstack.com结合的网页:

  • iPhone4S的
  • iPhone5的
  • iPhone5S
  • iPhone6
  • iPhone6 Plus
  • iPhone6S
  • iPhone6S Plus

全部使用RFC 6455

答案 2 :(得分:3)

我有类似的问题,甚至看过这篇文章找到它的修复程序。对我而言,它与无线连接无关。它似乎是websockets的iOS实现中的一个错误(甚至是当前版本5.1)。打开一堆XCode的调试,我发现它与内存管理有关,因为我会得到一些“发送到解除分配的实例的消息”。很可能有一个对象没有正确的引用计数,并且过早地清理过。

此博客有很多关于问题症状及其调试方法的重要信息,但没有解决方法:http://dalelane.co.uk/blog/?p=1652

最终,我发现了这种解决方法,我的应用程序几乎完全停止了崩溃。

me = this // strange javascript convention
this.socket = new WebSocket(url);
// put onmessage function in setTimeout to get around ios websocket crash
this.socket.onmessage = function(evt) { setTimeout(function() {me.onMessageHandler(evt);}, 0); };

答案 3 :(得分:2)

我让他们使用Chrome和Safari,iPhone和iPad(以及其他移动设备,但我猜你不介意它们)。这是我正在使用的Javascript代码:

<script language="javascript" type="text/javascript">

    var wsUri = document.URL.replace("http", "ws");
    var output;
    var websocket;


    function init()
    {
        output = document.getElementById("output");
        wsConnect();
    }

    function wsConnect()
    {
        console.log("Trying connection to " + wsUri);
        try
        {
            output = document.getElementById("output");
            websocket = new WebSocket(wsUri);
            websocket.onopen = function(evt)
            {
                    onOpen(evt)
            };
            websocket.onclose = function(evt)
            {
                    onClose(evt)
            };
            websocket.onmessage = function(evt)
            {
                    onMessage(evt)
            };
            websocket.onerror = function(evt)
            {
                    onError(evt)
            };
        }
        catch (e)
        {
            console.log("Exception " + e.toString());
        }
    }


    function onOpen(evt)
    {
        alert("Connected to " + wsUri);
    }

    function onClose(evt)
    {
        alert("Disconnected");
    }

    function onMessage(evt)
    {
        alert('Received message : ' + evt.data);
    }

    function onError(evt)
    {
        alert("Error : " + evt.toString());
    }

    function doSend(message)
    {
        websocket.send(message);
    }

    window.addEventListener("load", init, false);

调用doSend()函数完成从客户端到服务器的数据发送。从服务器接收数据也有效,我已经从自定义C ++服务器进行了测试。

答案 4 :(得分:1)

这是一个工作样本

Web套接字客户端

<!DOCTYPE html>
<meta charset="utf-8" />
<head>
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">

    var websocket;

function OpenWebSocket()
{

   try {
       websocket = new WebSocket(document.getElementById("wsURL").value);
       websocket.onopen = function(evt) { onOpen(evt) };
       websocket.onclose = function(evt) { onClose(evt) };
       websocket.onmessage = function(evt) { onMessage(evt) };
       websocket.onerror = function(evt) { onError(evt) };
   }
   catch(err) {
       writeToScreen(err.message);
   }
}

function CloseWebSocket()
{
     websocket.close();
}

function FindWebSocketStatus()
{
     try {
         if (websocket.readyState == 1){
          writeToScreen("Websocket connection is in open state")
         }
         else if (websocket.readyState == 0){
             writeToScreen("Websocket connection is in connecting state")
         }
         else{
          writeToScreen("Websocket connection is in close state")
         }
     }
     catch(err) {
         writeToScreen(err.message);
     }
}

function FindWebSocketBufferedAmount(){
    try {
            writeToScreen(websocket.bufferedAmount)
    }
    catch(err) {
        writeToScreen(err.message);
    }
}

function SendMessageThroughSocket(){
    doSend(document.getElementById("wsMessage").value);
}

function onOpen(evt)
{
    writeToScreen("Socket Connection Opened");
}

function onClose(evt)
{
    writeToScreen("Socket Connection Closed");
}

function onMessage(evt)
{
    writeToScreen('<span style="color: blue;">SERVER RESPONSE: ' + evt.data+'</span>');
}

function onError(evt)
{
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function doSend(message)
{
    try{
    writeToScreen("CLIENT SENT: " + message);
    websocket.send(message);
    }
    catch(err) {
        writeToScreen(err.message);
    }
}

function writeToScreen(message)
{
    var output = document.getElementById("output");
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
}
</script>
</title>
</head>
<body>
    <table>
        <tr>
            <td>
                WebSocket URL
            </td>
            <td>
                <input type="text" id="wsURL" value="ws://echo.websocket.org/"/>
            </td>
        </tr>
        <tr>
            <td>
                WebSocket Message
            </td>
            <td>
                <input type="text" id="wsMessage" value="Hi"/>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:left;">
                <input type="button" value="Open Socket Connection" onclick="OpenWebSocket();"/>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:left;">
                 <input type="button" value="Send Message" onclick="SendMessageThroughSocket();"/>
            </td>
        </tr>
        <tr>
          <td colspan="2" style="text-align:left;">
              <input type="button" value="Close Socket Connection" onclick="CloseWebSocket();"/>
          </td>
         </tr>
        <tr>
            <td colspan="2" style="text-align:left;">
                <input type="button" value="Find Socket Status" onclick="FindWebSocketStatus();"/>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:left;">
                <input type="button" value="Find Socket Buffered Amount" onclick="FindWebSocketBufferedAmount();"/>
            </td>
        </tr>
    </table>

<div id="output"></div>
</body>
</html>

Web套接字服务器

创建自己的套接字服务器也很简单只需安装 Node.js socket.io 然后通过 npm继续安装Web套接字

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
                               console.log((new Date()) + ' Received request for ' + request.url);
                               response.writeHead(404);
                               response.end();
                               });
server.listen(8888, function() {
              console.log((new Date()) + ' Server is listening on port 8888');
              });

wsServer = new WebSocketServer({
                               httpServer: server,
                               // You should not use autoAcceptConnections for production
                               // applications, as it defeats all standard cross-origin protection
                               // facilities built into the protocol and the browser.  You should
                               // *always* verify the connection's origin and decide whether or not
                               // to accept it.
                               autoAcceptConnections: false
                               });

function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    return true;
}

wsServer.on('request', function(request) {
            if (!originIsAllowed(request.origin)) {
            // Make sure we only accept requests from an allowed origin
            request.reject();
            console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
            return;
            }

            var connection = request.accept();
            console.log((new Date()) + ' Connection accepted.');
            connection.on('message', function(message) {
                          if (message.type === 'utf8') {
                          console.log('Received Message: ' + message.utf8Data);
                          connection.sendUTF('Message received at server:'+message.utf8Data);
                          }
                          else if (message.type === 'binary') {
                          console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
                          connection.sendBytes(message.binaryData);
                          }
                          });
            connection.on('close', function(reasonCode, description) {
                          console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
                          });
            });

NodeJS folder in finder

将上述文件另存为.js并从终端或命令提示符 node filename.js 运行

NodeJS

上面的文件就像我们首先使用节点创建了一个http服务器然后我们将创建的http服务器实例传递给Websocketserver然后传递给Socket.iO实例

答案 5 :(得分:1)

我正在调试一个类似的问题,并发现如果你使用https来获取网页,那么如果你使用传递,那么iOS将陷入困境:&#34; ws:&#34;协议到WebSocket。如果你使用&#34; wss:&#34;一切都会奏效,没有陷阱。