欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP Java Socket 通讯

程序员文章站 2022-04-23 17:57:26
...
PHP Java Socket 通信

Java写的Nio Socket Server端,需要从PHP写的页面发送命令过去。

?

Java Socket Server主要代码:

?public static void main(String args[]) {
??System.out.println("Start Server.....");
??try {
???ServerSocket server = new ServerSocket(8083);
???while(true) {
????Socket client = server.accept();
????System.out.println( client.getInetAddress().toString());
????BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
????PrintWriter pw = new PrintWriter(client.getOutputStream(),true);
????String m = br.readLine();? \\因为这里调用的是readLine()方法,默认读到\n才执行完毕。所以在PHP客户端传的的值末尾加上\n。 否则代码会停在这一行不往下执行。
????System.out.println("Client Message:" + m);
????System.out.println("Client IP:" + client.getInetAddress().toString());
????pw.write("Hello, I am from Java Server");
????pw.flush();
????pw.close();
????br.close();
????client.close();
????
????
???}
??} catch (IOException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
?}

?

?

?

PHP页面发送请求:

?$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die('Could Not Connect To Socket');
socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>1,"usec"=>0));

$connect = socket_connect($socket,'10.50.70.195',8083);
$output = iconv("utf-8","gbk","This is From Message\n");
socket_write($socket,$output,strlen($output));

//这一行注释? $str = socket_read($socket,1024,PHP_NORMAL_READ); 如果加上PHP_NORMAL_READ, PHP 客户端读不到Server端传回的值。并且报错:[function.socket-read]: unable to read from socket [0]:。。。。
$str = socket_read($socket,1024);
echo $str;
socket_close($socket);

?>

?

?

?

?

PHP Java Socket 通讯

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频