r/javahelp • • May 27 '19

Communication between 2 separately running java applications.

Just as the title implies, how can I share around some data from one java program to another running at the same time? I am trying using sockets but I am only able to establish a connection between a program and a local server but not sure how to connect the 2nd application to it. Edit : thanks everyone! I was using sockets previously so I needed to looking a simple chat example like you you suggested and was able to make 2 java classes one which was the client and the other server which is exactly what I needed!

28 Upvotes

12 comments sorted by

View all comments

2

u/ohjimmy May 27 '19 edited May 27 '19

Sometimes a stupid easy hack will do the trick. Have one application (A) write to a file. The other application (B) one could run in a tight loop (wake up ever 500 ms and see if the file exists) and poll to see if the file exists. If it does, read it.

To avoid having B read while A is writing, have A write to a temporary location and move the file to the expected location when it is finished writing. Generally the OS's file move operation is pretty atomic, and this should do the trick.

This technique is far from perfect, and isn't recommended for production level code, but is "good enough" for many uses, and a lot simpler than many of the other methods described, especially for someone new to java.