2011-08-24 79 views

回答

3

這會不會工作?

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

+0

我一直在試圖實現WebSockets,但問題是我們的生產服務器是相當安全的,即使安裝像node.js或socket.io服務是否有一個純粹的PHP5實現或只是JavaScript,我們可以上傳項目到網絡服務器和一切正常,沒有更多的安裝或配置要完成。可能嗎?我們使用cakePHP 2.3作爲我們的php框架 – indago

相關問題