1

I've the following code:

use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

$loop = \React\EventLoop\Factory::create();

$socketServer = new \React\Socket\Server('127.0.0.1:8080', $loop);

$httpServer = new \React\Http\Server(function(\Psr\Http\Message\ServerRequestInterface $request) {
  return new \React\Http\Response(200, [
      'Content-Type' => 'text/plain'
    ],
    'Hello, World'
  );
});

$httpServer->listen($socketServer);

$rrServer = new RRServer(); // Implements MessageComponentInterface

$webSocketServer = new IoServer(
  new HttpServer(
    new WsServer(
      $rrServer
    )
  ),
  $socketServer,
  $loop
);

$webSocketServer->run();

The code works, but I'm only able to access it using http://localhost:8080, and when I try to connect using WebSocket, the connection is opened, and then it immediately closes. Also, When I create a new socket with different port then I'm able to access both using http:// and ws://

What's wrong with my code? How can I run WebSocket and HTTP Server on the same port?

Malik Naik
  • 1,472
  • 14
  • 16

2 Answers2

4

Hey ReactPHP core team member here. In short you can listen with two servers on one port using so_reuseport on the socket server but that only sort of round robins connections to either of them. What you can do is try the suggestions cboden and I did here and lets us know if you had any issues with those: https://github.com/ratchetphp/Ratchet/issues/771#issuecomment-569439423

Which are namely:

thehennyy
  • 4,020
  • 1
  • 22
  • 31
WyriHaximus
  • 1,000
  • 6
  • 8
  • Thanks for the answer. For now, I've created two sockets one for handling WebSocket and another for handling HTTP Requests. – Malik Naik Dec 29 '19 at 15:36
1

Actually you can not run multi websocket in same port. but you can join all websockets in one. and separate them with url query like this.

and in your code can get source of request by :

function onOpen( ConnectionInterface $conn ) {
    $querystring = $conn->WebSocket->request->getQuery()->toArray();
    if($querystring['source'] == 'socket_1'){
        // run socket 1 jobs
    else{
        // do socket 2
    }
    // and change
}

I didnt do it and i didnt test it. so ... :)

ttrasn
  • 4,322
  • 4
  • 26
  • 43