简体   繁体   中英

TCP Server Java with PHP

JAVA CODE:

import java.io.*;
import java.net.*;

class Server {
   public static void main(String args[]) {
      try {
         ServerSocket srvr = new ServerSocket(51);
         Socket skt = srvr.accept();
         System.out.print("Server has connected!\n");
         PrintWriter out = 
                 new PrintWriter(skt.getOutputStream(), true);
         BufferedReader in = 
                 new BufferedReader(new InputStreamReader(skt.getInputStream()));
         if(in.readLine() == "xFF"){
             out.print("OK");
         }
         in.close();
         out.close();
         skt.close();
         srvr.close();
      }
      catch(Exception e) {
         System.out.print("Whoops! It didn't work!\n");
      }
   }
}

PHP CODE:

<?php
    $con = fsockopen("127.0.0.1", 51, $errno, $errstr, 10);
    fwrite($con, "xFF");
    if(fread($con, 256) == "OK"){
        // Its Works
    }
?>

The PHP Code return: Fatal error: Maximum execution time of 60 seconds exceeded in C:\\xampp\\htdocs\\index.php on line 7

if(in.readLine() == "xFF") => this will block forever since you do not send a newline character in your PHP script. Therefore you never send anything from your Java app and fread will never read anything at all. fwrite($con, "xFF\\n"); should do the trick.

If I guess right that you are trying to implement a "TCP-Server" with PHP. This is not possible is this kind you think:

Normally a PHP script will be terminated after 60 seconds. But you can override this behavoid is a .htaccess file, php.ini or with a php function.

.htaccess

<IfModule mod_php5.c>
php_value max_execution_time 500
</IfModule>

php.ini

Look for the line with max_execution_time and increase the value.

PHP

set_time_limit(0);

However I would recommend not to implement a server in PHP. PHP scripts should simply deliver fast some data and exit.

Your scripts is exceeding max execution time of 60 seconds increase it to 300 or more seconds like this

<?php
    ini_set('max_execution_time', 300); //max execution time set to 300 seconds
    $con = fsockopen("127.0.0.1", 51, $errno, $errstr, 10);
    fwrite($con, "xFF");
    if(fread($con, 256) == "OK"){
        // Its Works
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM