日期:2014-05-17  浏览次数:20481 次

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页面发送请求:

?<?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);

?>

?

?

?

?