4
votes

I'm trying to create a basic websocket chat from a tutorial in YouTube and I'am facing this error in the terminal when I run

php bin/server.php

Fatal error: Interface 'Ratchet\MessageComponentInterface' not found in /var/www/html/websocket/bin/chat.php on line 6

My code is as follows for chat.php:

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class chat implements MessageComponentInterface
    {
        protected $clients;
        public function __construct()
            {
                $this->clients=new \SplObjectStorage;
            }

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

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

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

        public function onError(ConnectionInterface $conn, \Exception $e)
            {
                echo "the following error occured: ".$e->getMessage();
                 $conn->close();
            }
    }

Code for server.php:

<?php
require 'chat.php';
require __DIR__ .'/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

$server=IoServer::factory(new HttpServer(new WsServer (new chat())) , 8080);
$server->run();

Any help would be appreciated.

2
Have you tried declaring the namespace first and set that, then used the use? php.net/manual/en/language.namespaces.importing.php I don't really use namespace all that much but the manual appears to do the namespace first, then the use.Rasclatt
well did that still not woking.shan2batman
You did namespace Ratchet;? Did you include the file that contains the Ratchet library?Rasclatt
yes i did, let me show you the code @Rasclattshan2batman
Where is your namespace though? Notice on the 2nd snippit: socketo.me/docs/hello-world It says namespace MyApp;Rasclatt

2 Answers

3
votes

Include the autoload.php file which has all the definitions for autoloading before using the Ratchet\MessageComponentInterface.

Include this code snippet just after defining the namespace:

require dirname(__DIR__) . '/vendor/autoload.php';

1
votes

go to the composer.json and change

{
    "require": {
        "cboden/ratchet": "^0.4"
    }
}

to

{
    "autoload": {
        "psr-4": {
            "MyApp\\": "src"
        }
    },
    "require": {
        "cboden/ratchet": "^0.4"
    }
}

and open command promote with administration update the composer like

composer update

you should have to be on the same folder directory where the composer.json is on