Home >Backend Development >PHP Tutorial >Simple method to use Socket in PHP
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 '**************************'; $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 = '192.168.1.100'; $post = 12299; $str = '{"@type":"xxx","args":[{"@type":"xxx","userInfo":{"nickname":"nickname", "phoneNo":"123143345345","roleType":"USER"}}],"methodName":"registerUser","serviceInterface":"xxx"}'; $back = 1; echo sendSocketMsg($host,$post,$str,$back);
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!