Java UDP Server, concurrent clients

Is there enough code to receive simultaneous UDP transmissions? More specifically, if 2 clients are simultaneously transmitting, will the DatagramSocket place the queues and pass them one by one, how do I call receive (), or will there be only one to skip it?

DatagramSocket socket = new DatagramSocket(port, address); byte[] buffer = new byte[8192]; while(!disconnect){ DatagramPacket p = new DatagramPacket(buffer, buffer.length); socket.receive(p); } 
+3
java udp sockets
source share
3 answers

By default there is no queue. The client may try again until a timeout or similar is reached. UDP works quietly, but under heavy load you may have clients that cannot connect.

+3
source share

If packets get to your network interface (imagine lost packets on an overloaded wireless channel), they will be skipped and the socket.receive(p) blocking method will be called. If there is a collision of packets on the channel due to the fact that two clients are transmitting simultaneously, you will not receive any of the two packets. But this, most likely, is impossible, because access technology to network interfaces will take care of this, check CSMA / CA or CSMA / CD

After calling socket.receive(p) you must create a new thread to process the packet itself. This ensures that the next packet can be received on the socket.

EDIT: Description of INTEL TX and RX Descriptors

0
source share

The main solution will be related to the thread responsible for processing several incoming requests (with your desired limit), and then transferring them to other worker / request handler threads. This basic structure is very similar to most servers: the main thread, which is responsible for sending requests to worker threads. When each of these workflows is complete, you can update the total / global counter so that the main thread knows that it can establish a new connection. This will require synchronization, but this is a simple and simple abstraction.

Here is an idea:

Server Subject :

 // Receive Packet while (true) { serverLock.acquire(); try { if (numberOfRequests < MAX_REQUESTS) { packet = socket.receive(); numberOfRequests++; requestThread(packet).run(); } else { serverMonitor.wait(serverLock); } } finally { serverLock.release(); } } 

Topic request :

 // Handle Packet serverLock.acquire(); try { if (numberOfRequests == MAX_REQUESTS){ numberOfRequests--; serverMonitor.pulse(); } } finally { serverLock.release(); } 

This is just to give you an idea of ​​where you can start. But when you hang it, you can make optimizations and improvements to make sure that the synchronization is correct.

One specific enhancement that also lends itself to a limited number of requests is called ThreadPool .

0
source share

All Articles