PHP Java Socket 通讯

WBOY
发布: 2016-06-13 12:55:59
原创
1035 人浏览过

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.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!