0

I want to work with websockets. I use XAMPP together with Windows 10. In the php.ini file i uncommented the ;extension=php_sockets.dll line so i think that websockets should be useable. But i still get the error Fatal error: Uncaught Error: Call to undefined function socket_create() This is my code:

<?php
    error_reporting(E_ERROR);
    set_time_limit (0);

    $host = 'localhost';
    $port = 1414;

    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    socket_bind($sock, $host, $port);

    socket_listen($sock);

    $sockets = array($sock);
    $arClients = array();

    while (true)
    {
        echo "Connecting...";

        $sockets_change = $sockets;
        $ready = socket_select($sockets_change, $write = null, $expect = null, null);

        echo "Connected!";

        foreach($sockets_change as $s)
        {
            if ($s == $sock)
            {
                $client = socket_accept($sock);
                array_push($sockets, $client);
                print_r($sockets);
            }
            else
            {
                $bytes = @socket_recv($s, $buffer, 2048, 0);
                $string = implode(array_map("chr",$bytes));
                if($string == ("hello world")){
                    socket_write($sock, "Hi");
                }
            }
        }
    }
?>

I use this javascript on the browser-side:

<script type="text/javascript">
    var ws_host = "localhost";
    var ws_port = "1414";
    var ws_server = "php_websockets_test.php";
    var ws_url = "ws://" + ws_host   + ":" + ws_port + "/" + ws_server;
    var socket;
    try{
        socket = new WebSocket(ws_url);
        socket.onopen = function(){
            alert("Connected successfully!");
        }
        socket.onmessage = function(msg){
            alert("Received: " + mgs);
        }
        socket.onclose = function(msg){
            alert("Connection closed. " + msg);
        }
    } catch(ex){
        alert("Exception: " + ex);
    }

    socket.send("hello world");
</script>

Now on page load i get Connection closed [Object CloseEvent]. Why is that?

binaryBigInt
  • 1,526
  • 2
  • 18
  • 44

0 Answers0