TARS-WEBSOCKET-SERVER Description

Directory Structure

  1. clients Stored a simple front page of the chat room, which contains two pages, each representing two chat rooms. Chat rooms can send messages to each other or broadcast globally.

  2. scripts Store the scripts required by the business, such as tars2php.sh, which is responsible for generating the code required by the client based on the tars file

3.src The directory where the business logic is located mainly contains the following structure:

  • component: Stores the basic class of the Controller, which is convenient for all Controllers, and stores the interface and an implementation of the fd used to store the websocket;

  • conf: configuration required by the business, here is just a demo, if the configuration is issued from the platform, it will also be written to this folder by default;

  • controller: C layer in MVC model;

  • message : Stores the files called after being triggered by the onMessage method of swoole;

  • servant: The client-side code generated by tars2php, this directory name can be completely customized, and only needs to be distinguished when it is used;

  • composer.json: state the project's dependencies

  • index.php: The entry file for the entire service. The file name can be customized, but the private template on the platform must be changed. The entry field is added under the server.

  • services.php: declare the base namespaceName of the entire project

3.tars The websocket service depends on the example.tars file under this folder; tars.proto.php is a necessary file for service packaging and publishing, where the APPName and ServerName must be exactly the same as those on the tars platform;

The tars.client.proto.php file is necessary to generate the code for the servant, which will be explained in the following guideline.

Demo description

This demo is to demonstrate the process of combining websocket and tarsphp. The request link is as follows:

  • client1.html initiates a websocket request to join room 1

  • tars-websocket receives the corresponding request, and after parsing, puts the fd of client1 into any storage with room 1 as the key (file in this example);

  • client2 has a similar process;

  • Through server->connections you can get all fds and perform broadcast operations;

Scene description:

  • A possible scenario is that the websocket service itself listens to the http port, triggers the interface externally, and then pushes messages to the browser

  • chatroom;

  • chatting software;

Service Deployment Guideline

  1. Enter Operations Management => Template Management

    The platform will provide a new template for PHP, named tars.tarsphp.default.

!!!!!!! You must first modify the execution path of PHP !!!!!!!

Secondly, there are two ways to ensure that the websocketserver uses the correct template:

  • Create a new tars.tarsphp.websocket yourself, add the following content:

<tars>
 <application>
...
    <client>
...
   </client>
   <server>
     ...
      protocolName=http
      servType=websocket
    </server>
 </application>
</tars>

Just add it in :

  protocolName=http
  • The second way is to add this part in the private template:

<tars>
 <application>
    <client>
   </client>
   <server>
      servType=websocket 
      protocolName=http
    </server>
 </application>
</tars>
  1. Enter Operations Management on the platform => Deployment Services, fill in the corresponding application name and service name, note that this is the same as tars.proto.php in the tars folder below Need to be completely consistent.

  2. Select the service type as tars_php

  3. Select the template as the websocket service template just created, set is not enabled by default

  4. Select an available port and fill in the server's intranet IP

  5. The port type is TCP !!!! Protocol type HTTP service must choose non-TARS !!!!!!

  6. The number of threads corresponds to the number of SWOOLE processes

  7. The maximum number of connections, the maximum queue length, and the queue timeout period are not effective for the PHP service.

  8. Click Add and Submit, then please enter the development guidline

Development guideline

  1. Create the corresponding directory structure, fixed to scripts, src and tars

  2. Create a new directory under src and copy the component and controller folders in the example

  3. Create a new composer.json file with the following content:

{
   "name" : "tars-http-server-demo",
   "description": "tars http server",
   "require": {
       "phptars/tars-server": "~0.2",
       "phptars/tars-deploy": "~0.1",
       "phptars/tars2php": "~0.1",
       "phptars/tars-log": "~0.1",
       "ext-zip" : ">=0.0.1"
   },
   "autoload": {
       "psr-4": {
           "HttpServer\\" : "./"
       }
   },
   "minimum-stability": "stable",
   "scripts" : {
       "deploy" : "\\Tars\\deploy\\Deploy::run"
   }
}

Among them, psr-4 in name, description, and autoload can be modified to what you need. Here we take this as an example.

  1. Create index.php under src with the following content:

    ```php

    <?php

    requireonce(_DIR."/vendor/autoload.php");

use \Tars\cmd\Command;

//php tarsCmd.php conf restart $config_path = $argv[1]; $pos = strpos($config_path,"--config=");

$config_path = substr($config_path,$pos+9);

$cmd = strtolower($argv[2]);

$class = new Command($cmd,$config_path); $class->run();

This file is responsible for startup and entry loading

5. Create a new services.php file with the following content:

```php  
<?php  
// Load the code in namespace mode under the framework of psr4
return [
    'obj' => [
        'namespaceName' => 'WebsocketServer\\',
        'home-class' => '\WebsocketServer\message\ExampleWebsocket',
        'saveTarsConfigFileDir' => 'src/conf/', //File save directory pulled from tarsconfig, Default is src/conf
        'saveTarsConfigFileName' => ['',], //The name of the file that needs to be pulled from tarsconfig. Configure on the web
        'monitorStoreConf' => [
            //Use redis to cache main report information
            //'className' => Tars\monitor\cache\RedisStoreCache::class,
            //'config' => [
            // 'host' => '127.0.0.1',
            // 'port' => 6379,
            // 'password' => ':'
            //],
            //Use swoole_table to cache the main report information (default)
            'className' => Tars\monitor\cache\SwooleTableStoreCache::class,
            'config' => [
                'size' => 40960
            ]
        ],
        'protocolName' => 'http', //http, json, tars or other
        'serverType' => 'websocket', //http(no_tars default), websocket, tcp(tars default), udp
    ]
];

namespaceName is the namespaceName actually used by the business and must correspond to the configuration in composer.json monitorStoreConf Storage configuration for the main report information

  • className The class name of the storage implementation class for the main report information. The default is \Tars\monitor\cache\SwooleTableStoreCache:: class uses swoole_table storage. redis is also provided in tars-monitor Storage method, users can also customize new implementation, but must implement \Tars\monitor\contract\StoreCacheInterface interface

  • config The configuration information of the storage implementation class for the main report information. It is passed in as a parameter when the implementation class is initialized. The default size is swoole_table

  1. composer install, load the corresponding dependencies

  2. Create a new conf directory to store the configuration under src. The default is ENVConf.php

  3. Create a new tars.proto.php file under the tars folder, which needs to include a description of your service itself:

<?php
return array(
    'appName' => 'PHPTest',
    'serverName' => 'PHPWebsocketServer',
    'objName' => 'obj',
);

This name must correspond exactly to the name on the tars platform.

  1. If you just try it, then you can skip to step 14 first if you need to call the tars service, please continue

  2. Put the hello.tars of tcp-server into the tars folder, and create a new tarsclient.proto.php file under the tars folder:

<?php
return array(
    'appName' => 'PHPTest',
    'serverName' => 'PHPServer',
    'objName' => 'obj',
    'withServant' => false,//Decide whether it is server-side or client-side automatic generation
    'tarsFiles' => array(
        './example.tars'
    ),
    'dstPath' => '../src/servant',
    'namespacePrefix' => 'HttpServer\servant',
);

APPName, serverName, objName must be exactly the same as those applied on the tars platform. withServant must be false, and specify the path of tarsFiles. dstPath is generally ../ src /?, here is ../ src / servant, so the generated code will go to this folder. namespacePrefix is the namespace of the corresponding code, here is HttpServer \ servant, which also corresponds to the name of psr-4 in composer.json.

  1. Running tars2php.sh under scripts will generate a three-level folder under src/servant,

cd ../tars/

php ../src/vendor/phptars/tars2php/src/tars2php.php ./tarsclient.proto.php

Here is PHPTest/PHPServer/obj

  • classes folder - Holds files generated by structs in tars

  • tars folder - stores tars files

  • TestTafServiceServant.php - the actual remote rpc call file

  1. Add the corresponding rpc calling code in the controller. For details, please refer to the demo in the code or the instructions of tars-client.

  2. After completing the code development, execute composer run-script deploy in the src directory to automatically package the code

  3. Upload the packaged code to the tars platform and publish it

  4. If you want to try out your own fd storage and deletion, please implement the FdStore interface under the component folder.

Last updated