Search code examples
phphtmlwebsocketphpwebsocket

Can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);


I am using javascript to connect websocket:

<script>
    var socket;  
    var host = "ws://localhost:8000/socket/server/startDaemon.php";  
    var socket = new WebSocket(host);  
</script>

I got the error:

Can't establish a connection to the server at

var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);

How can I solve this issue?

NOTE : I enabled websocket in mozilla to support web socket application. and when i run in chrome i got error:

   can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);

Solution

  • I solved my error by following code through this link

    http://www.flynsarmy.com/2010/05/php-web-socket-chat-application/ and created socketWebSocketTrigger.class.php file for response message where code as

    class socketWebSocketTrigger
    {   
    
            function responseMessage($param)
            {
                $a = 'Unknown parameter';
    
                if($param == 'age'){
                    $a = "Oh dear, I'm 152";
                }
    
                if($param == 'hello'){
                    $a = 'hello, how are you?';
                }
    
                if($param == 'name'){
                    $a = 'my name is Mr. websocket';
                }
    
                if($param == 'today'){
                    $a = date('Y-m-d');
                }
    
                if($param == 'hi'){
                    $a = 'hi there';
                }
    
                return $a;
    
            }
    
    }
    

    and added code in send function of 'WebSocketServer.php' for calling 'responseMessage' function which response request message

     public function send($client, $msg){
            $this->say("> ".$msg);
            $messageRequest = json_decode($msg,true);
    
                // $action=$messageRequest[0];
                $action = 'responseMessage';
                $param  = $messageRequest[1]['data'];
            if( method_exists('socketWebSocketTrigger',$action) ){
                                    $response = socketWebSocketTrigger::$action($param);
                                }
                $msg = json_encode(
                    array(                      
                    'message',
                        array('data' => $response)
                    )
                );
    
                $msg = $this->wrap($msg);
    
            socket_write($client, $msg, strlen($msg));
        }
    

    it's working great.