For php‑ocket communication, the NioSocketServer written in Java needs to send commands from the pages written in PHP .? JavaSocketServer main code :? Publicstaticvoidmain (Stringargs []) {? System. out. println (StartServer .....);?? Try {PHP Java Socket communication
The Nio Socket Server written in Java needs to send commands from the pages written in PHP.
?
Java Socket Server 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 the readLine () method is called here, the execution is completed only after \ n is read by default. Therefore, add \ n to the end of the value passed by the PHP client. Otherwise, the code will stop in this line and will not be executed.
???? 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 sending request:
? $ 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 ));
// Comment this line? $ Str = socket_read ($ socket, 1024, PHP_NORMAL_READ); if PHP_NORMAL_READ is added, the PHP client cannot read the value returned by the Server. In addition, the following error occurs: [function. socket-read]: unable to read from socket [0]:...
$ Str = socket_read ($ socket, 1024 );
Echo $ str;
Socket_close ($ socket );
?>
?
?
?
?