Php and java implement code through socket communication. 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: Copy the code as follows: importjava. io. *; importjava.net. *; a simple function implemented by pub demo is to accept the string written by the PHP end and return it to the output end as it is. 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 will listen to Port 5678. after receiving the message, it will return 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.
Bytes. The code is as follows: Code: import java. io. *; import java.net. *; pub...