簡體   English   中英

Javascript客戶端如何連接到PHp套接字服務器?

[英]How can Javascript client connect to PHp socket Server?

嗨,我有一個用PHP編寫的運行套接字服務器。

服務器正在偵聽連接..任何想法我的客戶端(用javascript編寫)將如何連接到服務器並向其發送數據?

PS:我只知道如何將php客戶端連接到套接字服務器,但不確定如何連接javascript客戶端。

謝謝大家的時間。

回答一個老問題以防萬一人們通過Google找到它。

如今幾乎所有當代瀏覽器都支持WebSocket Javascript API。 通過WS,瀏覽器中的客戶端JS可以打開全雙工套接字到用PHP或其他語言編寫的服務器。 服務器必須實現WS協議,但現在有用於PHP,Java和其他語言的WS庫。

在撰寫本文時,WS實現似乎仍然是一個移動目標,但是,我目前正在使用與WS / Java服務器通信的WS / JS瀏覽器客戶端,它似乎確實有效。

使用您選擇的服務器語言為WS實現建議Google搜索。

希望這可以幫助!

我為客戶端使用標准的WebSocket API 和服務器端的核心PHP套接字

知道,發送和接收數據使用帶有websocket的瀏覽器上的標題。 但代碼PHP套接字,無標頭發送和接收,只發送普通數據。

所以我們需要在socketing服務器端模擬標頭。

為了學習並知道如何做,我寫了這個清晰的示例代碼,使用此代碼,您可以向服務器發送一個短語並在客戶端接收反向短語。

server.php

<?php
//Code by: Nabi KAZ <www.nabi.ir>

// set some variables
$host = "127.0.0.1";
$port = 5353;

// don't timeout!
set_time_limit(0);

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0)or die("Could not create socket\n");

// bind socket to port
$result = socket_bind($socket, $host, $port)or die("Could not bind to socket\n");

// start listening for connections
$result = socket_listen($socket, 20)or die("Could not set up socket listener\n");

$flag_handshake = false;
$client = null;
do {
    if (!$client) {
        // accept incoming connections
        // client another socket to handle communication
        $client = socket_accept($socket)or die("Could not accept incoming connection\n");
    }

    $bytes =  @socket_recv($client, $data, 2048, 0);
    if ($flag_handshake == false) {
        if ((int)$bytes == 0)
            continue;
        //print("Handshaking headers from client: ".$data."\n");
        if (handshake($client, $data, $socket)) {
            $flag_handshake = true;
        }
    }
    elseif($flag_handshake == true) {
        if ($data != "") {
            $decoded_data = unmask($data);
            print("< ".$decoded_data."\n");
            $response = strrev($decoded_data);
            socket_write($client, encode($response));
            print("> ".$response."\n");
            socket_close($client);
            $client = null;
            $flag_handshake = false;
        }
    }
} while (true);

// close sockets
socket_close($client);
socket_close($socket);

function handshake($client, $headers, $socket) {

    if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
        $version = $match[1];
    else {
        print("The client doesn't support WebSocket");
        return false;
    }

    if ($version == 13) {
        // Extract header variables
        if (preg_match("/GET (.*) HTTP/", $headers, $match))
            $root = $match[1];
        if (preg_match("/Host: (.*)\r\n/", $headers, $match))
            $host = $match[1];
        if (preg_match("/Origin: (.*)\r\n/", $headers, $match))
            $origin = $match[1];
        if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
            $key = $match[1];

        $acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
        $acceptKey = base64_encode(sha1($acceptKey, true));

        $upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
            "Upgrade: websocket\r\n".
            "Connection: Upgrade\r\n".
            "Sec-WebSocket-Accept: $acceptKey".
            "\r\n\r\n";

        socket_write($client, $upgrade);
        return true;
    } else {
        print("WebSocket version 13 required (the client supports version {$version})");
        return false;
    }
}

function unmask($payload) {
    $length = ord($payload[1]) & 127;

    if ($length == 126) {
        $masks = substr($payload, 4, 4);
        $data = substr($payload, 8);
    }
    elseif($length == 127) {
        $masks = substr($payload, 10, 4);
        $data = substr($payload, 14);
    }
    else {
        $masks = substr($payload, 2, 4);
        $data = substr($payload, 6);
    }

    $text = '';
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i % 4];
    }
    return $text;
}

function encode($text) {
    // 0x1 text frame (FIN + opcode)
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if ($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)$header = pack('CCS', $b1, 126, $length);
    elseif($length >= 65536)
    $header = pack('CCN', $b1, 127, $length);

    return $header.$text;
}

client.htm

<html>
<script>
//Code by: Nabi KAZ <www.nabi.ir>

var socket = new WebSocket('ws://localhost:5353');

// Open the socket
socket.onopen = function(event) {
    var msg = 'I am the client.';

    console.log('> ' + msg);

    // Send an initial message
    socket.send(msg);

    // Listen for messages
    socket.onmessage = function(event) {
        console.log('< ' + event.data);
    };

    // Listen for socket closes
    socket.onclose = function(event) {
        console.log('Client notified socket has closed', event);
    };

    // To close the socket....
    //socket.close()

};
</script>
<body>
<p>Please check the console log of your browser.</p>
</body>
</html>

手動:首先在CLI上運行php server.php ,然后在瀏覽器上打開http://localhost/client.htm

你可以看到結果:

http://localhost/client.htm
> I am the client.
< .tneilc eht ma I

php server.php
< I am the client.
> .tneilc eht ma I

請注意,它只是測試發送和接收數據的示例代碼,對執行工作沒有用。

我建議你使用這些項目:

https://github.com/ghedipunk/PHP-Websockets
https://github.com/esromneb/phpwebsocket
https://github.com/acbrandao/PHP/tree/master/ws
https://github.com/srchea/PHP-Push-WebSocket/
http://socketo.me/

我還建議您閱讀這些文章以獲取更多詳細信息:

http://www.abrandao.com/2013/06/websockets-html5-php/
http://cuelogic.com/blog/php-and-html5-websocket-server-and-client-communication/
http://srchea.com/build-a-real-time-application-using-html5-websockets

我不知道為JS提供任意套接字功能的任何東西。 Web Sockets的支持有限(我認為這需要您修改服務器以符合空間)。 如果做不到這一點,簡單的XHR可能會滿足您的需求(這需要您修改服務器以充當Web服務)。 如果服務在與頁面不同的原點上運行,那么您將需要使用CORS或使用諸如JSONP之類的解決方案

簡而言之 - 你不能這樣做 - 讓客戶端代碼打開套接字連接是一個安全漏洞。

但是,您可以模擬 - 將您的數據作為AJAX請求發送到另一個PHP頁面,然后使該PHP頁面通過套接字進行通信。

2017年更新

與此同時, websockets成了一件事。 請注意,websocket協議與通用網絡套接字不同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM