PHP的socket串連到服務端模版,socket服務端_PHP教程

來源:互聯網
上載者:User

PHP的socket串連到服務端模版,socket服務端


在整理新架構的時候,發現對於一些快取資料,需要對外的介面訪問,而比較方便的是php的介面,所以臨時研究了下php如何串連java服務端。

先貼上代碼:
  1. php
  2. require_once 'CRC16.php';
  3. /*-----------------------------
  4. | 向伺服器發送資料包
  5. ------------------------------*/
  6. classServer{
  7. //發送資料包
  8. publicstaticfunction sendPacket($packet, $host, $port){
  9. $protocol ='tcp';
  10. $get_prot = getprotobyname ( $protocol );
  11. //建立socket
  12. $socket = socket_create ( AF_INET, SOCK_STREAM, $get_prot );
  13. //建立串連
  14. $conn = socket_connect ( $socket, $host, $port );
  15. if(!$conn){
  16. socket_close($socket);
  17. exit("socket connect failed!");
  18. }
  19. $buffer =@socket_read($socket,9, PHP_NORMAL_READ);
  20. $crcCode =(ord($buffer[7])<<8)+ord($buffer[8]);
  21. $len = strlen($packet);
  22. $newpacket = CRC16::encode($packet, $crcCode,4);
  23. socket_send ( $socket, $newpacket, $len,0);
  24. //等待接受
  25. $head =@socket_read($socket,4,PHP_NORMAL_READ);
  26. $len =(ord($head[0])<<24)+(ord($head[1])<<16)+(ord($head[2])<<8)+ord($head[3]);
  27. $content =@socket_read($socket,$len-4,PHP_NORMAL_READ);
  28. socket_close ( $socket );
  29. return substr($content,3);
  30. }
  31. publicstaticfunction packet($group,$cmd,$message){
  32. $size = strlen($message)+8;
  33. $str ='';
  34. $str .=self::writeInt($size);
  35. $str .=self::writeByte(0);
  36. $str .=self::writeByte($group);
  37. $str .=self::writeByte($cmd);
  38. $str .=self::writeByte(1);
  39. $str .= $message;
  40. return $str;
  41. }
  42. //寫進2個byte的資料
  43. privatestaticfunction writeShort($s){
  44. return pack ("n", $s );
  45. }
  46. //寫進4個byte的資料
  47. privatestaticfunction writeInt($N){
  48. return pack ("N", $N );
  49. }
  50. //寫進1個byte的資料
  51. privatestaticfunction writeByte($b){
  52. return pack ("c", $b );
  53. }
  54. }
因為個人服務端串連之後,會分配一個crcCode校正碼,發送的訊息需要進行crc16的加密(其實很簡單的,保持點神秘感),所以先等待接受固定長度來獲得crcCode,然後發送請求後,等待接受資料包,並返回。



來自為知筆記(Wiz)




PHP的Socket怎進行服務端與用戶端的相互連信?

伺服器提供資料緩衝區,並提供一種使用者識別機制。以此來給聊天使用者雙方發送相應的資訊。
看似使用者與使用者之間的通訊實質上是使用者在與伺服器通訊。
我的一點理解
 

php socket串連不上

查一下連接埠把
 

http://www.bkjia.com/PHPjc/880092.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/880092.htmlTechArticlePHP的socket串連到服務端模版,socket服務端 在整理新架構的時候,發現對於一些快取資料,需要對外的介面訪問,而比較方便的是php的介面,...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.