how to make websocket for secure using wss

31 Views Asked by At

I use this code but is not create websocket connection in secure website but work in localhost plz tell me the correct code for secure websocket connection code using wss

this code is run in localhost but wehn i upload in server the this error are show "chat.html:11 WebSocket connection to 'wss://0.0.0.0:9502/' failed:"

php-socket.php  code 
define("HOST_NAME", "chat.mitco.pk");
define("PORT", "9443");
$null = null;

require_once "socket_class.php";
$mysocket = new Socket();

$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socketResource, 0, PORT);
socket_listen($socketResource);
$keys = [];
session_start();
$clientSocketArray = [$socketResource];

while (true) {
    $newSocketArray = $clientSocketArray;
    socket_select($newSocketArray, $null, $null, 0, 10);

    if (in_array($socketResource, $newSocketArray)) {
        $newSocket = socket_accept($socketResource);
        $clientSocketArray[] = $newSocket;

        $header = socket_read($newSocket, 1024);

        $mysocket->doHandshake($header, $newSocket, "ssl://" . HOST_NAME, PORT);

        socket_getpeername($newSocket, $client_ip_address);
        $id = isset($_GET["id"]) ? $_GET["id"] : 0;
        $connectionACK = $mysocket->newConnectionACK($client_ip_address, $id);

        $mysocket->send($connectionACK);

        $newSocketIndex = array_search($socketResource, $newSocketArray);
        unset($newSocketArray[$newSocketIndex]);
    }

    foreach ($newSocketArray as $newSocketArrayResource) {
        while (
            socket_recv($newSocketArrayResource, $socketData, 1024, 0) >= 1
        ) {
            $socketMessage = $mysocket->unseal($socketData);
            $messageObj = json_decode($socketMessage);

            $chat_box_message = $mysocket->createChatBoxMessage($messageObj);
            $mysocket->send($chat_box_message);
            break 2;
        }

        $socketData = @socket_read(
            $newSocketArrayResource,
            1024,
            PHP_NORMAL_READ,
        );
        if ($socketData === false) {
            socket_getpeername($newSocketArrayResource, $client_ip_address);
            $connectionACK = $mysocket->connectionDisconnectACK(
                $client_ip_address,
            );
            $mysocket->send($connectionACK);
            $newSocketIndex = array_search(
                $newSocketArrayResource,
                $clientSocketArray,
            );
            unset($clientSocketArray[$newSocketIndex]);
        }
    }
}
socket_close($socketResource);

socket_class.php code

class Socket {
    
    function send($message) {
        global $clientSocketArray;
        $messageLength = strlen($message);
        foreach($clientSocketArray as $clientSocket)
        {
            @socket_write($clientSocket,$message,$messageLength);
        }
        return true;
    }

    function send1($message) {
        global $clientSocketArray;
        $messageLength = strlen($message);
        foreach($clientSocketArray as $clientSocket)
        {
            @socket_write($clientSocket,$message,$messageLength);
        }
        return true;
    }

    function unseal($socketData) {
        $length = ord($socketData[1]) & 127;
        if($length == 126) {
            $masks = substr($socketData, 4, 4);
            $data = substr($socketData, 8);
        }
        elseif($length == 127) {
            $masks = substr($socketData, 10, 4);
            $data = substr($socketData, 14);
        }
        else {
            $masks = substr($socketData, 2, 4);
            $data = substr($socketData, 6);
        }
        $socketData = "";
        for ($i = 0; $i < strlen($data); ++$i) {
            $socketData .= $data[$i] ^ $masks[$i%4];
        }
        return $socketData;
    }

    function seal($socketData) {
        $b1 = 0x80 | (0x1 & 0x0f);
        $length = strlen($socketData);
        
        if($length <= 125)
            $header = pack('CC', $b1, $length);
        elseif($length > 125 && $length < 65536)
            $header = pack('CCn', $b1, 126, $length);
        elseif($length >= 65536)
            $header = pack('CCNN', $b1, 127, $length);
        return $header.$socketData;
    }



        function doHandshake($received_header, $client_socket_resource, $host_name, $port)
        {
            $headers = array();
            $lines = preg_split("/\r\n/", $received_header);
            foreach ($lines as $line) {
                $line = chop($line);
                if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
                    $headers[$matches[1]] = $matches[2];
                }
            }
        

            
            // if (isset($headers['Sec-WebSocket-Key'])) {
                
            //  $secKey = $headers['Sec-WebSocket-Key'];
            //  // Rest of your code here
            // } else {
                

            //  // Handle the case where the key is not set
            //  $secKey ='';
                
            // }

            if (isset($headers['Sec-WebSocket-Key'])) {
                $secKey = $headers['Sec-WebSocket-Key'];
                // Your further code handling here
                
            } else {
                // Handle the case where 'Sec-WebSocket-Key' is not set
            
                $magicString = bin2hex(random_bytes(16));
                $randomString = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 16);

                // Base64 encode the random string
                $secWebSocketKey = base64_encode($randomString);
                $responseKey = base64_encode(sha1($secWebSocketKey . $magicString, true));

                // Send the response headers
                 $rskey=$responseKey."=" ;
                
                $secKey = $rskey;
            }

        

    // $secKey = $headers['Sec-WebSocket-Key'];
    // $secKey = $headers['HTTP_SEC_WEBSOCKET_KEY'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host_name\r\n" .
        "WebSocket-Location: wss://$host_name:$port/demo/php-socket.php\r\n" .  // Change ws to wss
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_socket_resource, $buffer, strlen($buffer));
}

    
    function newConnectionACK($client_ip_address) {
        $message = 'New client ' . $client_ip_address.' joined';
        $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }
    
    function connectionDisconnectACK($client_ip_address) {
        $message = 'Client ' . $client_ip_address.' disconnected';
        $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack',"type"=>"disconnected");
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }
    
    function createChatBoxMessage($data) {
            $chatMessage = $this->seal(json_encode($data));
        return $chatMessage;
    }
}
?>     ```
 please help me to make a correct code for wss websocket in php


0

There are 0 best solutions below