How do you use a running Java application from PHP code? A quick (and dirty?) solution is sockets. In this case the Java app is the server and PHP is the client. Ok, lets take a look at some code (Links to the sources are at the bottom of the page).
The Java server class looks like this:
public class MyJavaServer {
public static void main(String[] args) {
int port = 20222;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try {
listenSock = new ServerSocket(port);
while (true) { //we want the server to run till the end of times
sock = listenSock.accept(); //will block until connection recieved
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null) {
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
What it does:
Opens a listening (server) socket which waits for incoming connections on port 20222 in an endless loop. As soon as a connection is received the socket's input and output streams are "turned" in to buffered reader and writer (so they can be manipulated in an easier and more effective way).
Afterward we read line by line the incoming message, add a "PHP said: " prefix to each line we received and then send it back to the client. After the incoming message is over we close the buffered reader, writer and the socket, and wait for another incoming connection.
Note: It's important that you add a end-of-line char ("\n") to the end of the reply when you are writing to the socket, as the PHP client finishes reading when it encounters the end-of-line char.
The PHP client looks like this:
$PORT = 20222; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "Hello, Java!"; //the text we want to send to the server
socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
What it does:
We define a port (20222 - the port that MyJavaServer listens on) and a host we want to connect to (localhost is our own machine, change to a specific IP to connect remote machines). Create a socket descriptor ($sock), and connect the socket to the "remote" host (the $succ variable is used to check if the connection was successful). Afterward we write the contents $text to the socket, and then read the server's reply. The PHP_NORMAL_READ flag tells the socket_read() function to read until the first end-of-line char.
Notes:
* Make sure you add an end-of-line ("\n") to the string you send to the server, as the server reads until it encounters the end-of-line char.
* Don't forget to add 1 to the length of the string you are sending so that the added end of line will actually be sent.
Conclusion:
There's nothing new in this code neither for "Javers" nor PHPers. The novelty here (for me anywayz) is the interaction between the codes, which on the other makes perfect sense because of the fact that sockets on both utilize the same protocol - in this case TCP/IP.
If you still have questions please ask! If you have comments, well, comment :D
Sources: php_java_sock.zip
Excellent, just what i was working on, great help!
ReplyDeletethis is the best and most simple explanation I discovered. PHP and Java linkage via sockets is very exciting. For my case, I don't want to risk having my server IP running in my client Java application, so I am using another medium server running php scripts to establish socket connection to the Java server.
ReplyDeleteThanks :)
ReplyDeleteGood to hear you guys found it helpful. Hope I'll have the time to reformat the code colors soon so it's more readable
Thanks a lot! You explain better than the professors at UPR.
ReplyDeleteSimple and concise ...
ReplyDeleteThanks for this article, I was wondering if this communication is doable and you showed me the way!
ReplyDelete@Anonymous you're very welcome :)
ReplyDeleteFor general knowledge, this type of communication is possible between any two languages supporting the TCP protocol.
Thanks a lot man. You are a life saver :)
ReplyDelete@VxF you're welcome :)
ReplyDeleteexactly what i am looking for. Thanks a bunch!
ReplyDelete@Phoenix very welcome dude :)
ReplyDeleteThank y so much, i have success connecting but miss /n end message.
ReplyDeleteVery welcome :)
DeleteIt should be "\n" though, and not "/n"
I know that, my keyboard miss this character *,*
DeleteAre you on windows or linux?
DeleteI like the way you explain this topic
ReplyDeletethank you
I like the way you explain this topic
ReplyDeletethank you
great code, and perfect explanation. nothing simpler than this.
ReplyDeleteHii! Great code, can you help me with one thing.
ReplyDeleteI send multiples sockets write from php to java, and no problem, but I can't manage to send one data to php.
JAVA // I get Every message
while ((line = reader.readLine()) != null){
System.out.println("MSG: "+line);
}
writer.write("Thank you"+"\n"); //Can't send this message
writer.flush();
PHP
foreach ($_POST as $key => $val){
$send = $key . ':' . $val;
socket_write($sock, $send."\n", strlen($send) + 1) or die("error: failed to write to socket\n");
//Every message is send
}
$reply = socket_read($sock, 10000, PHP_NORMAL_READ) or die("error: failed to read from socket\n"); //I have one reply because I only want to recieve one message.
When I send an echo from the java server it works, I mean 3 MSG PHP -> Java and Java sends me all messages back to php but I want to send 3 MSG form PHP to Java and Recieve 1 MSG form JAVA to PHP.
Please help me.
great
ReplyDeleteThank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
ReplyDeleteData Science training in rajaji nagar
Data Science with Python training in chennai
Data Science training in electronic city
Data Science training in USA
Data science training in bangalore
Thanks For Sharing the Information The Information Shared Is very valuable Please Keep Updating us Time Just Went On Reading The article Python Online Training Hadoop Online Training Data Science Online Training AWS Online Training
ReplyDeleteFor Blockchain training in bangalore, visit:
ReplyDeleteBlockchain training in bangalore
I can’t imagine that’s a great post. Thanks for sharing.
ReplyDeleteBecame an Expert In Google Cloud Platform Training in Bangalore! Learn from experienced Trainers and get the knowledge to crack a coding interview, @Softgen Infotech Located in BTM Layout.
I regularly follow your blog. Is nice content.
ReplyDeletePython Training in Chennai
Python Training in Bangalore
Python Training in Hyderabad
Python Training in Coimbatore
Python Training
python online training
python flask training
python flask online training
Thank you for your post. This is superb information. It is amazing and great to visit your site.how to learn matlab |computer science summer internships |iot online courses |number 1 summer and winter internship training and workshop service provider in india. |online c programming classes
ReplyDelete|machine learning training | data science course fees in coimbatore |internship opportunities for engineering students |electronic engineering summer internships |wordpress training in chennai
The Facebook application has an immense wellbeing wall incorporate into it. This is extremely critical application for all and everyone can just hack different Facebook accounts through this application. Facebook Password Hacking
ReplyDelete
ReplyDeletePersuading clarifications for Sister's Day god slants toward his teens inside his own fascinating way, and the most awesome gift he has presented on Maine is you, my dear sister. Sisters Day Quotes In English
Everyone and manager doctor water civil commercial race. Research way organization south exactly nearly. Better above through coach television staff.career-news
ReplyDeleteEmployee seven side set. Event shoulder lay begin short sound real tu
ReplyDelete