$ svn checkout http://phpdaemon.googlecode.com/svn/trunk $path/
$ chmod +x $path/bin/phpdaemon
$ pecl install libevent
$ ln -s $path/bin/phpdaemon /usr/bin/phpd
Copy Source | Copy HTML
- <? php
- // Turn On Error Display
- error_reporting (E_ALL);
- ini_set ( 'display_errors' , '1' );
- return array (
- 'mod-websocketserver-enable' => 1 , // Turn on the web socket server
- 'mod-websocketserver-listen' => 'tcp: //0.0.0.0' , // Listen to all IP
- 'mod-websocketserver-listenport' => 8047 , // Hang to a different one from 80 so as not to conflict with other web servers
- 'max-requests' => 1000 , // Maximum number of requests
- 'max-idle' => 0 , // Maximum idle time
- 'user' => 'www' , // User
- 'group' => 'www' , // and the group under which the daemon runs
- 'min-spare-workers' => 5 ,
- 'max-spare-workers' => 20 ,
- 'start-workers' => 1 ,
- 'max-workers' => 50 ,
- 'min-workers' => 1 ,
- 'path' => dirname ( __FILE__ ). '/appResolver.php'
- );
- ?>
Copy Source | Copy HTML
- <? php
- return new WebSocketWorker;
- / ** <br/> * WebSocket Handler <br/> * <br/> * /
- class WebSocketWorker extends AppInstance {
- / ** <br/> * WebSocket Server <br/> * @var WebSocketServer <br/> * /
- public $ ws ;
- / ** <br/> * Initialization handler <br/> * /
- public function onReady () {
- $ this -> ws = Daemon :: $ appResolver -> getInstanceByAppName ( 'WebSocketServer' );
- if ( $ this -> ws) {
- $ this -> ws-> routes [ 'myRoute' ] = array ( $ this , 'openSession' );
- }
- }
- / ** <br/> * Opening a new session <br/> * @param $ client <br/> * /
- public function openSession ( $ client ) {
- return new WebSocketWorkerSession ( $ client );
- }
- }
- / ** <br/> * Websocket Session <br/> * <br/> * /
- class WebSocketWorkerSession {
- public $ client ;
- / ** <br/> * Initialization <br/> * @param $ client <br/> * /
- public function __construct ( $ client ) {
- Daemon :: log ( 'connected' );
- $ this -> client = $ client ;
- }
- / ** <br/> * Receiving message <br/> * @param $ data - message body <br/> * @param $ type - message type <br/> * /
- public function onFrame ( $ data , $ type ) {
- Daemon :: log ( $ data );
- if ( $ data === 'ping' ) {
- $ this -> client-> sendFrame ( 'pong' );
- }
- }
- / ** <br/> * Closing session <br/> * /
- public function onFinish () {
- }
- }
- ?>
Copy Source | Copy HTML
- <script type = "text / javascript" >
- <! -
- if ( "WebSocket" in window) {
- var ws = new WebSocket ( "ws: //127.0.0.1: 8047 / myRoute" );
- ws.onopen = function () {
- // Web Socket is connected. You can send data using the send () method.
- ws.send ( "ping" );
- };
- // every time the browser gets some data through a web socket
- ws.onmessage = function (evt) {
- alert ( 'Received message:' + evt.data);
- };
- ws.onclose = function () {
- // websocket closed.
- };
- } else {
- // for browsers that do not support WebSocket.
- alert ( 'Your browser does not support websockets' );
- }
- // ->
- </ script>
Source: https://habr.com/ru/post/82140/
All Articles