Home > Backend Development > PHP Tutorial > Simple method to use Socket in PHP

Simple method to use Socket in PHP

小云云
Release: 2023-03-21 09:56:01
Original
1609 people have browsed it

This article mainly shares with you the simple use of Socket in PHP, hoping to help everyone.


<?php
/*socket收发数据    
    @host(string) socket服务器IP
    @post(int) 端口
    @str(string) 要发送的数据
    @back 1|0 socket端是否有数据返回
    返回true|false|服务端数据
  */
function sendSocketMsg($host,$port,$str,$back=0){   
 echo &#39;**************************&#39;;   
 $socket = socket_create(AF_INET,SOCK_STREAM,0);
  if ($socket < 0) return false;
  $result = @socket_connect($socket,$host,$port);
  if ($result == false)return false;  
  socket_write($socket,$str,strlen($str));
  socket_shutdown($socket);
  if($back!=0){
    $input = socket_read($socket,5000);
    socket_close ($socket);
    return $input;
}else{
    socket_close ($socket);
    return true;
}}
 
$host = &#39;192.168.1.100&#39;;
$post = 12299;
$str = &#39;{"@type":"xxx","args":[{"@type":"xxx","userInfo":{"nickname":"nickname",
"phoneNo":"123143345345","roleType":"USER"}}],"methodName":"registerUser","serviceInterface":"xxx"}&#39;;
$back = 1;
 
echo sendSocketMsg($host,$post,$str,$back);
Copy after login

Related recommendations:

Tutorial on setting up and testing Socket server in PHP

Detailed examples of how to use Socket in WeChat applet

PHP combined with examples to understand what Socket is

The above is the detailed content of Simple method to use Socket in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template