Home > Article > Backend Development > Detailed explanation of PHP request Socket interface test example
This article mainly introduces the detailed explanation of PHP request Socket interface test examples. Interested friends can refer to it. I hope it will be helpful to everyone.
Use php to read the data of the socket interface, pass the request method and request parameters through php, and get the return result
PHP file:
<?php class Test{ const IP='127.0.0.1'; const port=10003; public static function main(){ header("Content-type:text/html;Charset=UTF-8"); $socket=new Test(); $result=$socket->connSocket("getmaillist\r\n{'id':2}\r\n"); echo $result; } private function connSocket($str){ $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); $res=@socket_connect($socket,self::IP,self::port); if(!$res){ return; } socket_write($socket,$str); $result=""; while($data = socket_read($socket,1024)){ $result.=$data; } socket_close($socket); return $result; } } Test::main();
Java Socket server:
import java.io.InputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Test { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(10003); while (true) { Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); byte[] b = new byte[1024]; int len = is.read(b); String inputString = new String(b, 0, len); PrintWriter pw=new PrintWriter(socket.getOutputStream(),true); String result=""; //处理发来的数据 if(inputString.contains("\r\n")){ String[] params=inputString.split("\r\n"); if(params[0].equals("getmaillist")){ String maillist=getmaillist(); result="请求方法:"+params[0]+",请求参数:"+params[1]+",请求结果:"+maillist; }else{ result="非法参数2"; } }else{ result="非法参数1"; } pw.println(result); socket.close(); } } public static String getmaillist(){ return "中国上海/2015年7月28日——服务于中国及全球华人社群的领先在线媒体公司新浪公司(Nasdaq GS: SINA)定于美国当地时间2016年8月8日周一股市收盘后公布截至2016年6月30日的2016第二季度未经审计的财务报告。随后,新浪管理团队将于美国东部时间晚10点10分召开电话会议,通报公司的财务和经营状况。"; } }
Effect:
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
Detailed explanation of usage of PHP passing parameters by reference
php Detailed explanation of the Alibaba Cloud OSS image upload class
##
The above is the detailed content of Detailed explanation of PHP request Socket interface test example. For more information, please follow other related articles on the PHP Chinese website!