I have client server application – client on C++ (running on AIX,using library ), and server on Java (running on Win and on AIX, using java.net., java.io.).
Structure of application is next
Server
//...
while (true)
{
final Socket s = ss.accept();
pool.execute(new Service(s));
}
// ..
Service.class get byte from input strean and send bytes to otputstream. And close Socket s
Cleint is
SendMessage(msg)
{
// ...
const int socketFD = OpenSocket();
// send bytes
// receive bytes
close(socketFD);
}
Question is next: can I once open socket on client-side,
send message, receive message and after some time send new mesage
and receive new message.
without reopen socket?
Sure you can. The server, however, should understand that more than one message is expected, and should not kill Service until client closes connection. The problem with your implementation, is that Service is a Runnable and not a Thread. If it would loop on receiving messages, it will keep the thread it is running on. If you use FixedThreadPool, this can make a situation when all the pool threads are exhausted and next Service would wait until one of the previous client disconnects. Using CachedThreadPool avoids this, but as a result, the number of threads used is equal to the number of clients. This is not a problem if you have enough main memory (each thread uses roughly 0.5 Mb). If you want to save memory, you can use asynchronous network libraries like Apache Netty. Java 7 has asynchronous channels implemented.
https://github.com/rfqu/df4j is a lightweight dataflow library, which includes a wrapper over Java7 async network facilities to make them easier to use.