amir
amir

Reputation: 2573

request from php to java server

excuse me . I am new in web development . I have an simple java server that listen to port 12111 on localhost . here is there :

public static void doit() throws IOException {

    ServerSocket m_ServerSocket = new ServerSocket(12111);
    int id = 0;
    while (true) {
        Socket clientSocket = m_ServerSocket.accept();
        ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
        cliThread.start();
    }
}

now I have an php script in server which the java there . now I want to send request to this port . when I run java server on this port , i type localhost:12111 and run . now no matter post or get request sent . what code I have to write in php ? thank you .

Upvotes: 1

Views: 354

Answers (2)

Halayem Anis
Halayem Anis

Reputation: 7785

Using PHP CURL (you must activate php_curl.dll in php.ini and restart your Apache Server):

# WARNING : maybe you should provide your context in the URL : provide the same URL that you use in your browser for example
$url = "http://127.0.0.1:12111";
#provide your parameters like : ?param1=value1&param2=value2&.....&paramN=valueN
$post_params_s = "" ;

$ch  = curl_init ( $url ) ;
curl_setopt ( $ch, CURLOPT_POST          , TRUE ) ;
curl_setopt ( $ch, CURLOPT_POSTFIELDS    , $post_params_s ) ;
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE ) ;             // -- put it to FALSE, write directly in main output
curl_exec   ( $ch ) ;
curl_close  ( $ch ) ;

Using Socket (Your Java Server will read and send data by Socket)

$service_port = 12111;
$address = "127.0.0.1";

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    print "Java Server Is down, or firewall protected";
    exit 1;
}

$result = socket_connect($socket, $address, $service_port);
if ($socket === false) {
    print "fatal error, (details)" . socket_strerror(socket_last_error($socket));
    exit 2;
} 

# YOU SHOUL PROVIDE YOUR REQUEST DATA IN THIS VARIABLE
$in = "";
$out = '';

socket_write($socket, $in, strlen($in));
$out = socket_read($socket, 2048);
print "received data : " . $out;

socket_close($socket);

Hope that helps :)

Upvotes: 1

Halayem Anis
Halayem Anis

Reputation: 7785

At least you have 2 diffrents ways to contact your Java Server from PHP:

  • Using PHP Sockets
  • Using PHP CURL

Upvotes: 1

Related Questions