java - how to send instruction to server every five second -
i have written part of code server receive instruction client , send request client. want send instruction(json message) client every 5 second. how that?
public static void main(string[] args) throws ioexception, interruptedexception, parseexception { synchronisedfile fromfile = null; fromfile=new synchronisedfile("file.txt"); fromfile.checkfilestate(); int counter = 1; int receivedcounter = 1; string receivedtype=null; datagramsocket clientsocket = new datagramsocket(); inetaddress ipaddress = inetaddress.getbyname("localhost"); byte[] senddata = new byte[1024]; byte[] receivedata = new byte[1024]; while(true){ instruction inst = fromfile.nextinstruction(); //system.out.println(inst.tojson()); jsonobject jo = new jsonobject(); jo.put("type", "inst"); jo.put("inst", inst.tojson()); jo.put("counter", counter); //system.out.println(jo); counter++; senddata = jo.tostring().getbytes(); datagrampacket sendpacket = new datagrampacket(senddata, senddata.length, ipaddress, 4144); clientsocket.send(sendpacket); datagrampacket receivepacket = new datagrampacket(receivedata, receivedata.length); clientsocket.receive(receivepacket); string receivedmessage = new string(receivepacket.getdata()); string subreceivedmessage = receivedmessage.trim(); final jsonparser parser = new jsonparser(); jsonobject obj; obj = (jsonobject) parser.parse(subreceivedmessage);
you use scheduledexecutorservice
. here basic example using returned result using (callable
) below. if don't need result can use runnable
method instead similar signature:
scheduledexecutorservice scheduledexecutorservice = executors.newscheduledthreadpool(10); scheduledfuture<string> scheduledfuture = scheduledexecutorservice.schedule(new callable<string>() { @override public string call() throws exception { return "result"; } }, 5, timeunit.seconds);
Comments
Post a Comment