Tools

Java and C++ Socket Communication

The C++ Windows Application

Let's examine the C++ Windows server application, which also uses sockets to communicate over the network. This implementation is unaware of whether the client connecting to it is written in Java, C/C++, or any other language. The use of XML further ensures that the communication will succeed.

When the server application starts, an instance of the ServerSocket class is created (Listing Three and the complete C++ server are available here) which listens on port 8080 for new client connections. In summary, this class uses Windows Sockets to create a network socket, and then listen on it and accept new client connection requests as they arrive:

Given that the call to accept() blocks until a new client connects, this code is executed in its own thread. Once a client does connect, the resulting code is similar to the Java socket implementation in that objects are created to handle sending data over the socket, and listening for data to arrive:

Conclusion

You should now have a basic understanding of how Java and C/C++ applications can communicate via network socket programming. In fact, although the sample server application explored here uses Windows sockets, a comparable Linux application can be developed to work equally well with the Java client presented here. Combined with XML, this should provide a suitable solution in some cases. To learn about other application integration techniques, such as with JNI, JMS, or web services, take a look at the following articles:

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!