The communication between PHP and java through socket is no different from the basic sockent programming. One read and one write are just for the convenience of writing in java and PHP.
The communication between PHP and java through socket is no different from the basic sockent programming. One read and one write are just for the convenience of writing in java and PHP.
The simple function implemented by the demo is to accept the strings written by the PHP end and return them to the output end as they are. The Code is as follows:
The Code is as follows:
Import java. io .*;
Import java.net .*;
Public class Server {
Public static void main (String [] args) throws IOException {
System. out. println ("Server started! \ N ");
ServerSocket server = new ServerSocket (5678 );
While (true ){
Socket client = server. accept ();
System. out. println ("client coming! \ N ");
PrintWriter printer = new PrintWriter (client. getOutputStream ());
BufferedReader reader = new BufferedReader (new InputStreamReader (client. getInputStream ()));
String m = reader. readLine ();
System. out. println ("get infomation" + m + "\ n from" + client. getInetAddress (). toString ());
Printer. println (m );
Printer. flush ();
Printer. close ();
Printer. close ();
Client. close ();
System. out. println ("client leaving! \ N ");
}
}
}
After running, the java program listens to port 5678. After receiving a message, it returns the received message to the client as it is ......
The PHP code is as follows:
The Code is as follows:
$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ('could not create socket ');
$ Connect = socket_connect ($ socket, '192. 0.0.1 ', 127 );
// Send data to the server
Socket_write ($ socket, 'Hello'. "\ n ");
// Accept the data returned by the server
$ Str = socket_read ($ socket, 1024, PHP_NORMAL_READ );
Echo $ str;
// Close
Socket_close ($ socket );
The PHP program connects to port 5678 of the Local Machine, writes Hello, and then reads the returned data ...... Output the returned data to the browser ......
Run the java Server first, and then access the PHP page in a browser. The Hello message returned from the server is displayed.