socket communication between a Java and/or C++ programs (现成的程序)
If you need to do socket communication between a Java and/or C++ programs, you've come to the right place. I've developed a fairly basic class that can be used to communicate between Java applications and C++ programs via a socket connection. There are client and server classes for both Java and C++, so you could use these classes for communication between the same language or between languages.
The classes below have been tested and seem to work. You must of course balance your sends and receives otherwise it will stall. You will have to determine whether the byte order needs to be reversed between your client and server. It appears that byte order will need to reversed if one side is Java and the other side is C++. If both sides are the same language, you should be okay without reversing them.
Efficiency isn't the best. I worked some time to get the classes to perform as well as they do. Sending and receiving of bytes is fairly fast, but other types require the Java side to convert the data array to an array of bytes. This was necessary in order to get the data to be sent in bigger, more efficient blocks. I suspect the conversion could be done faster than my stream technique, but I have not pursued it.
The fastest method I found to send data was using the datagram methods. Be careful, since this is not a guaranteed delivery form of communication, packets can and do get lost in transit. You'll need to do some sort of communication via the normal send and receive routines to provide resending of missing packets.
For more details about the implementation, there is a section in the my thesis project paper.
A lot of the C code for the socket routines I lifted from the excellent tutorial: Beej's Guide to Network Programming. For a starting point on the Java code, I used the book: Java: How to Program, Deitel & Deitel.
Client.java | Socket client written in Java |
Server.java | Socket server written in Java |
client.cpp | Socket client written in C++ |
client.h | Header file for the C++ client |
server.cpp | Socket server written in C++ |
server.h | Header file for the C++ server |
Makefile | Makefile for all for the above and the test programs |
server_test.cpp | Simple test program of the C++ server |
client_test.cpp | Simple test program of the C++ client |
java_server_test.java | Simple test program of the Java server |
java_client_test.java | Simple test program of the Java client |
socket.tar | All the above in a convenient tar file |
swarm_monitor.tar | A example using the socket library to measure performance on an MPI network. |