2016-10-25 52 views
0

我目前正在使用websocket使用TLS/SSL(wss://)實時通知服務。
我對瀏覽器和服務器之間的握手有一些問題。一切工作正常與服務器和客戶端在PHP中,但當我使用JS的WebSocket連接到服務器,它失敗,因爲我不知道如何處理服務器端(從瀏覽器)握手。

到目前爲止,我的服務器代碼:SSL websocket在php/javascript

$host = '127.0.0.1'; 
$port = '9000'; 
$null = NULL; 

$context = stream_context_create(); 

// local_cert must be in PEM format 
stream_context_set_option($context, 'ssl', 'local_cert', "cert.pem"); 
stream_context_set_option($context, 'ssl', 'local_pk', "key.pem"); 
// Pass Phrase (password) of private key 
stream_context_set_option($context, 'ssl', 'passphrase', "test"); 
stream_context_set_option($context, 'ssl', 'allow_self_signed', true); 
stream_context_set_option($context, 'ssl', 'verify_peer', false); 

// Create the server socket 
$server = stream_socket_server('ssl://' . $host . ':' . $port, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context); 

if ($server == false) { 
    die ("Could no create the server."); 
} 

//start endless loop 

while (true) { 
    $buffer = ''; 
    print "waiting..."; 
    $client = stream_socket_accept($server); 
    var_dump($client); 
    print "accepted " . stream_socket_get_name($client, true) . "\n"; 
    if ($client) { 
     stream_set_blocking($client, true); 
     // TODO : handshaking 
     stream_set_blocking($client, false); 

     // Respond to php client (test only) 
     /*fwrite($client, "200 OK HTTP/1.1\r\n" 
      . "Connection: close\r\n" 
      . "Content-Type: text/html\r\n" 
      . "\r\n" 
      . "Hello World!"); 
     fclose($client);*/ 
    } else { 
     print "error.\n"; 
    } 
} 

沒有什麼是陳述有關的RFC WebSocket SSL握手。
如果有人對如何實現握手有一些想法,將不勝感激。

回答

1

沒有關於RFC WebSocket上的SSL握手。

wss://只是ws://在SSL連接內部,與HTTPS僅僅是SSL連接內的HTTP相同。沒有什麼特別之處,即您只需在成功的SSL握手之後在SSL流上說出WebSocket協議即可。

+0

我明白了,謝謝澄清。然而從維基百科,服務器返回'HTTP/1.1 101交換協議 升級:網頁套接字 連接:升級 仲丁基的WebSocket - 接受:HSmrc0sMlYUkAGmm5OPpG2HaGWk = 仲丁基網頁套接字協議:chat' 此爲'WS://'插座,我不應該爲'wss://'websocket返回不同的東西嗎? –

+0

@AlexandreChambet:不,請求發送的升級是相同的,響應也是一樣的。唯一的區別是通過普通的TCP連接進行通信,而通過SSL流進行通信。與HTTP與HTTPS完全相同。 –

+0

謝謝,我會考慮一下。 –