ip_dispatch.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. $serv = new swoole_server("0.0.0.0", 9501);
  3. $serv->fdlist = [];
  4. $serv->workerid = 0;
  5. $serv->set(array(
  6. //'tcp_defer_accept' => 5,
  7. //'ipc_mode' => 2,
  8. 'worker_num' => 4,
  9. //'task_worker_num' => 2,
  10. 'dispatch_mode' => 4, //ip dispatch
  11. //'max_request' => 1000,
  12. //'daemonize' => true,
  13. //'log_file' => '/tmp/swoole.log'
  14. ));
  15. $serv->on('workerStart', function($serv, $worker_id) {
  16. echo "{$worker_id} start".PHP_EOL;
  17. $serv->workerid = $worker_id;
  18. });
  19. $serv->on('connect', function ($serv, $fd, $reactor_id){
  20. //echo "[#".posix_getpid()."]\tClient@[$fd:$reactor_id]: Connect.\n";
  21. echo "{$fd} connect, worker:".$serv->workerid.PHP_EOL;
  22. $conn = print_r($serv->connection_info($fd));
  23. $serv->fdlist[$fd] = 1;
  24. print_r($serv->fdlist);
  25. });
  26. $serv->on('task', function ($serv, $task_id, $reactor_id, $data){
  27. //var_dump($task_id, $reactor_id, $data);
  28. $fd = $data;
  29. $serv->send($fd, str_repeat('B', 1024*rand(40, 60)).rand(10000, 99999)."\n");
  30. });
  31. $serv->on('finish', function ($serv, $fd, $reactor_id){
  32. });
  33. $serv->on('receive', function (swoole_server $serv, $fd, $reactor_id, $data) {
  34. foreach($serv->fdlist as $_fd=>$val) {
  35. $serv->send($_fd, "{$fd} say:".$data.PHP_EOL);
  36. }
  37. });
  38. $serv->on('close', function ($serv, $fd, $reactor_id) {
  39. //echo "[#".posix_getpid()."]\tClient@[$fd:$reactor_id]: Close.\n";
  40. unset($serv->fdlist[$fd]);
  41. });
  42. $serv->start();