如何每五秒钟向服务器发送一次指令

时间:2014-09-20 03:58:43

标签: java json sockets udp

我已经编写了部分代码,服务器将从客户端接收指令并将请求发送回客户端。 但我想每隔五秒钟从客户端发送指令(Json消息)。我怎么能这样做?

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);

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您可以使用ScheduledExecutorService。以下是使用下面的(Callable)返回结果的基本示例。如果您不需要返回结果,则可以使用Runnable方法,而不是类似的签名:

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
ScheduledFuture<String> scheduledFuture = scheduledExecutorService.schedule(new Callable<String>() {
    @Override
    public String call() throws Exception {
        return "Result";
    }
}, 5, TimeUnit.SECONDS);