PHP Java Socket Communication
Java writes the NIO Socket server side and needs to send commands past the page written from PHP.
?
Java Socket Server main code:
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 ();? \ \ Because this is called the ReadLine () method, the default read \ n is executed. So add \ n at the end of the value passed by the PHP client. Otherwise the code will stop in this line and not execute down.
???? 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 page Send request:
? $socket = socket_create (af_inet,sock_stream,sol_tcp) or Die (' Could does 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 was from message\n");
Socket_write ($socket, $output, strlen ($output));
This line of comment? $str = Socket_read ($socket, 1024,php_normal_read); If you add Php_normal_read, the PHP client cannot read the value returned by the server side. and error: [Function.socket-read]: Unable to read from socket [0]: ....
$str = Socket_read ($socket, 1024);
Echo $str;
Socket_close ($socket);
?>
?
?
?
?