tabuna / web-socket

Laravel library for asynchronously serving WebSockets.
MIT License
219 stars 29 forks source link

Error establishing connection #10

Closed sarfraznawaz2005 closed 7 years ago

sarfraznawaz2005 commented 7 years ago

I am getting errors establishing connection, this is what i have done:

class MySocket extends BaseSocketListener {

 protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        $conn->close();
    }

}

JS:

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

socket.onopen = function() {
  alert("The connection is established.");
};

socket.onclose = function(event) {
  if (event.wasClean) {
    alert('Connection closed cleanly');
  } else {
    alert('Broken connections'); 
  }
  alert('Key: ' + event.code + ' cause: ' + event.reason);
};

socket.onmessage = function(event) {
  alert("The data " + event.data);
};

socket.onerror = function(error) {
  alert("Error " + error.message);
};

//To send data using the method socket.send(data).

//For example, the line:
socket.send("Hello");

Started server (php artisan socket:serve) Laravel web socket server started on localhost:8080/address:127.0.0.1

Route:

$socket->route('/socket', new \App\Http\Sockets\MySocket, ['*']);

But Iam getting erorrs like:

WebSocket connection to 'ws://localhost/' failed: Error during WebSocket handshake: Unexpected response code: 200

Broken connections Key: 1006 cause:

Any ideas plz ?

tabuna commented 7 years ago

Hi Sarfraz Ahmed, i looked at your code, and the problem in connecting to js. You need to specify the route that uses your socket and port

 var socket = new WebSocket("ws://localhost:8080/socket");

Write it and everything will be fine

sarfraznawaz2005 commented 7 years ago

@tabuna Awesome thanks it works now :)

anil1712 commented 6 years ago

Hi, It is not working for me. It is showing the "Connection Established" alert but in chrome console its throwing exception

socket.html:110 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

Please give me some suggestion on the same