test.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. // Server
  3. class Server
  4. {
  5. private $serv;
  6. public function __construct() {
  7. $this->serv = new swoole_server("0.0.0.0", 9099);
  8. $this->serv->set(array(
  9. 'worker_num' => 8,
  10. 'daemonize' => false,
  11. 'max_request' => 10000,
  12. 'dispatch_mode' => 2,
  13. 'debug_mode'=> 1,
  14. // 'open_length_check' => true,
  15. //'package_length_type' => 'N',
  16. ));
  17. $this->serv->on('Start', array($this, 'onStart'));
  18. $this->serv->on('Connect', array($this, 'onConnect'));
  19. $this->serv->on('Receive', array($this, 'onReceive'));
  20. $this->serv->on('Close', array($this, 'onClose'));
  21. $this->serv->start();
  22. }
  23. public function onStart( $serv ) {
  24. echo "Start\n";
  25. }
  26. public function onConnect( $serv, $fd, $from_id ) {
  27. $serv->send( $fd, "Hello {$fd}!" );
  28. }
  29. public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
  30. //$data = iconv('GBK','UTF-8', $data);
  31. //$str = base64_encode($data);
  32. //$str = unpack('h*', $str);
  33. //print_r($str) . "\n";
  34. $data = bin2hex($data);
  35. echo "客户端响应 {$fd}:{$data}\n";
  36. fwrite(STDOUT,"请输入:");
  37. $str = trim(fgets(STDIN));
  38. //$str = pack('H*', $str);
  39. $str = str_replace(' ', '', $str);
  40. $str = hex2bin($str);
  41. if($str)
  42. {
  43. $serv->send( $fd, $str );
  44. }
  45. }
  46. public function onClose( $serv, $fd, $from_id ) {
  47. echo "Client {$fd} close connection\n";
  48. }
  49. }
  50. // 启动服务器
  51. $server = new Server();