简体   繁体   中英

TimerTask in java and web socket

I'm trying to write a basic client server using Java's DatagramSocket and DatagramPacket classes. I have the basic code set up, but I want a way to send 100 messages from my Client to my Server at regular intervals ie 1 sec, or 2 sec, or 5 sec.

Basically, I want something like:

while (count != 0)
sleep (1);
create message packet;
send message packet;
count--;

In C there's a sleep method, but I'm not sure how to do that in java. Anyone have any suggestions?

You can always call Thread.sleep() , which is largely equivalent to the sleep function from C. But I would recommend an alternative route to accomplishing your program. Take a look at the ScheduledThreadPoolExecutor class, it allows you to schedule a piece of code to be run at regular intervals:

Runnable myCommand = new Runnable() {
    public void run() {
        // Do some work
    }
};

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4);
// Execute the command every second = 1000 milliseconds
executor.scheduleAtFixedRate(myCommand, 0, 1000, TimeUnits.MILLISECONDS);
Timer timer = new Timer();
timer.schedule(new Task(), 1000); //schedule the task to be run at 1 second (1000 mili sec) time

Here is the code for Task class

class Task extends TimerTask
{
    Task()
    {
    }

    public void run()
    {
        //create datagram socket
        //create datagram packet
        //send the packet
    }
}

Java is pretty high level than C. (of course you have thread libs in C too :), what I meant this is supported as Java language support than libraries)

So, you can use Timer class.

Coming to the main functionality you will have something like

DatagramSocket socket = new DatagramSocket();
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName("sample-address");
DatagramPacket packet = new DatagramPacket
                    (buf, buf.length, 
                    address, 4445);
socket.send(packet); 

In that class implementing TimerTask.

Have to override a run method there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM