It depends which kind of connections you want you use, if you remember Java has either blocking I/O (java.net.Socket
, java.net.ServerSocket
) and unblocking I/O throught channels (java.nio.channel.SocketChannel
)
In a blocking I/O approach every client would have its own producer/consumer handling, you can have:
- a thread that consumes answers that are queued locally and tries to dispatch them to the server
- the GUI that cares about placing items in the answer's queue
whenever your consumer thread is able to send an answer to the server, it removes it from the queue
While on the server you can process answers in a common place:
- you have a thread that processes answers received from all clients (you can accumulate them in a buffer) and it puts itself in wait when the buffer is empty.
- every connection from a client has it's own thread that receives answers and places them in the process queue.
This approach is safe but it's quite heavy weight. You can think about opening a connect just for the time of an answer, dispatch it to the server and then close.
Otherwise you can simply use UDP (that is actually better for this kind of problem) but you will have to think about a way to send acknowledgments back to the clients whenever your server receives an answers.
For example:
- student gives an answer: the answer is added to the client buffer
- client thread tries to send its buffer over UDP
- whenever a client receives an acknowledge for an answers it removes it from the buffer
- it tries periodically to send still unacknowledged answers
On server side:
- whenever it receives an answer datagram from a client accumulate it on the process buffer
- you have a thread that processes all the answers on the buffer
- the server will send back an ackknowledge to the client to warn that answer has been received
But this is still not sure because the ackowledge can be missed on the net.
In any case you could use ObjectInputStream
and ObjectOutputStream
to pass directly objects between clients and server. So you can think an encapsulated object like
class Answer
{
int studentId;
int questionId;
int answer;
}