Miky
Miky

Reputation: 942

How to write an UDP server that will service n concurrent requests from different clients?

I am connecting 10 devices to a LAN, all of them have a udp server that goes like:

while(true){
   serverSocket.receive(receivePacket);
   dostuff(receivePacket);
}
serverSocket.close();

Now lets assume 9 of the devices try to initiate connection to the 10th device simultaenously. How can I accept all 9 instead of just the first which will then block the socket untill the server completes computation? Should I start a thread which will take care of dostuf() ? Will this let me get request from all of the simultaneous requests I got?

Upvotes: 2

Views: 1599

Answers (3)

ligerdave
ligerdave

Reputation: 772

Use a relatively larger size threadpool since udp doesn't require response.

main method will run as a listener and a threadpool will be doing rest of the heavy lifting

Upvotes: 1

Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

A basic design would have on thread responsible for handling incoming requests (with your desired limit) and then handing them off to worker/request handler threads. When each of these worker threads is finished, you'd want to update a shared/global counter to let the main thread know that it can establish a new connection. This will require a degree of synchronization, but it can be pretty fun.

Here's the idea:

serverThread:
    while true:
        serverLock.acquire()

        if numberOfRequests < MAX_REQUESTS:
            packet = socket.receive()
            numberOfRequests++
            requestThread(packet).run()
        else
            serverMonitor.wait(serverLock);

        serverLock.release()

requestThread:
    //handle packet

    serverLock.acquire()

    if numberOfRequests == MAX_REQUESTS:

    numberOfRequests--
        serverMonitor.pulse();

    serverLock.release()

You'll want to make sure the synchronization is all correct, this is just to give you an idea of what you can start out with. But when you get the hang of it, you'll be able to make optimizations and enhancements. One particular enhancement, which also lends itself to limited number of requests, is something called a ThreadPool.

Regardless the basic structure is very much the same with most servers: a main thread responsible for handing off requests to worker threads. It's a neat and simple abstraction.

Upvotes: 3

fabricemarcelin
fabricemarcelin

Reputation: 1759

You can use threads in order to solve that problem. Since java already has an API that handles threads you can just create instance of runnable executors, take a look at the Executor Interface. Here is another useful link that could potentially help: blocking queue

Upvotes: 1

Related Questions