使用php socket 发送tcp请求

2018-08-20 03:50:40   php分享记录

 

使用php socket 发送tcp请求

  1. /**
  2. * 沟通业务员坐席 执行摘机操作(拨打以及接听操作用)
  3. * @param Request $request
  4. * @return \Illuminate\Http\JsonResponse
  5. */
  6. public function ConnectedToSoft(Request $request){
  7. $user_info = Session::get('user_info');
  8. $ip = $request->getClientIp();
  9. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  10. //设置接受超时2秒
  11. socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 2, "usec" => 0));
  12. socket_connect($socket, $ip, 8888);
  13. //里面的换行代表 \r\n 注意拷贝的代码后面可能有空格
  14. $http = json_encode(array('username' => $user_info['systemPhone'], 'password' => "1111111", 'action' => "answer"));
  15. socket_write($socket, $http, strlen($http));
  16. $strs = "";
  17. while ($str = socket_read($socket, 1024)) {
  18. $strs .= $str;
  19. }
  20. $return_infos = json_decode($strs, true);
  21. if ($return_infos['status'] === "success") {
  22. return \response()->json(array('status'=>"200"));
  23. } else {
  24. return \response()->json(array('status'=>"401"));
  25. }
  26. }