I have a datagramsocket in a thread. My confusion is this:
I want to only invoke it only when a packet is received.
Above snippet is inside a try catch block, but I just didn't show it. The problem with the above snippet is that when this thread is run, and no packet is received it will just wait until a packet is received. What I want is to only invoke the socket.receive(packet) if a packet is present, so the application can do other things.
The functionality you are looking for is in java.nio.channels.DatagramChannel. You can configure it to return immediately if there are no packets waiting to be read. [ August 16, 2005: Message edited by: Joe Ess ]
NIO is poorly documented, compared to the standard IO classes. Since it is not as widely used as standard IO, you won't get the same level of help in forums, either. If you are serious about using it, I recommend you study the existing documentation and buy a book. If you don't want to risk it, create one listening thread per connection. Unless you have several thousand simultaneous connections you should be fine.
Thread1: Listen indefinitely until packet is received Packet finally received, so process yield so other thread can run
You realize that since this code blocks on the call to receive(), that yield() doesn't get invoked until AFTER a packet is received? Being nice to other threads is a Good Thing, but since receive() blocks, another thread would get control immeditately if there were no data to be processed.
Originally posted by Karen Baog:
The problem I see with the above "approach" is that it is not a good approach, for the resource to be tied up until a packet is received is such a waste.
Like I said above, unless you have thousands of simultaneous connections, this won't be a problem. You could use a low-latency protocol where the client only connects when it has a request (HTTP works this way), to reduce the amount of time a client connection blocks a thread. NIO's always an option. I haven't done much with it. There's an article on Building Highly Scalable Servers with NIO but like I said before, if you run into trouble, there's not a lot of experience with NIO in the community.
I also new to NIO. I have to develop a host. in this case there can be 1000 connections in same time. So I tried with old ServerSocket but it can not handle it. So i tried with NIO. In this case the ServerSocketChannel get some time to give response. So i set the timeout in client side as 30000 milliseconds . But this not good. Because our system is a transport ticketing system. So customer can not wait 30 seconds as maximum in traffic hours. So are their any suggestions for do this? In initial step the system has 5000 terminals for issue tickets. My ServerSocketChannel code is just like the code inside of this link http://docs.oracle.com/javase/1.5.0/docs/guide/nio/example/NBTimeServer.java.