1. function socketSendMsg($url,$ip,$port,$sourcePort=8294)
    2. {
    3. // Create a new socket
    4. $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    5. // An example list of IP addresses owned by the computer
    6. $sourceips['kevin'] = '127.0.0.1';
    7. $sourceips['madcoder'] = '127.0.0.2';
    8. // Bind the source address, $sourcePort是发起端主机绑定的端口
    9. socket_bind($sock, '0.0.0.0',$sourcePort);
    10. // Connect to destination address
    11. socket_connect($sock, $ip, $port);
    12. // Write
    13. $http = "GET {$url} HTTP/1.1\r\n";
    14. $http.="Host: {$ip}:{$port}\r\n";
    15. $http.="Content-type:application/json;charset=utf-8\r\n";
    16. $http.="Connection:Close\r\n\r\n";
    17. socket_write($sock, $http);
    18. //socket_read()
    19. //$message = array();
    20. //socket_recvmsg($sock,$message);
    21. $msg = '';
    22. while (true) {
    23. $buf = "";
    24. if (false !== ($bytes = socket_recv($sock, $buf, 2048, MSG_WAITALL))) {
    25. if($bytes===0){
    26. break;
    27. }
    28. $msg .= $buf;
    29. }else{
    30. break;
    31. }
    32. }
    33. // Close
    34. socket_close($sock);
    35. $arr = explode("\r\n",$msg);
    36. $jsonStr = $arr[count($arr)-1];
    37. $resp = json_decode($jsonStr,true);
    38. return $resp;
    39. //var_dump($buf);
    40. }