简体   繁体   English

Java如何等待命令完成?

[英]Java how to wait until a command has completed?

I have the following script: 我有以下脚本:

    Connection con = new Connection("host",80);

    ByteBuffer loginbb = ByteBuffer.allocate(300);
    <snip>
    loginbb.flip();

    byte[]login = new byte[loginbb.remaining()];
    loginbb.get(login);


    ByteBuffer headerbb = ByteBuffer.allocate(7);
    <snip>
    headerbb.flip();

    byte[]header = new byte[headerbb.remaining()];
    headerbb.get(header);

    con.run(login, header);


    try {
        Thread.sleep(1000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }


    long pid = Long.parseLong(request.getParameter("player"));
    PrintWriter out = response.getWriter();
    ByteBuffer bb = ByteBuffer.allocate(100);
    bb.putLong(pid);
    bb.putLong(pid);
    bb.put((byte) 0x00);
    bb.flip();

    byte[] payload = new byte[bb.remaining()];
    bb.get(payload);


    ByteBuffer headerbb2 = ByteBuffer.allocate(7);
    <snip>
    headerbb2.flip();

    byte[]header2 = new byte[headerbb2.remaining()];
    headerbb2.get(header2);

    con.send(payload, header2);

    try {
        Thread.sleep(700);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(Avatar.getJson().toString());
    String json = gson.toJson(je);
    out.flush();
    out.println(json);
    out.flush();

Notice the following? 请注意以下内容?

    try {
        Thread.sleep(700);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

and this: 和这个:

    try {
        Thread.sleep(1000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

So that is pausing my script for some time but I don't want it like that as the script may take longer or less time. 所以这会暂停我的脚本一段时间,但是我不希望这样,因为脚本可能会花费更长或更短的时间。 That would be a waste of some time D: 那会浪费一些时间D:

What I want to happen is that it just waits for the stuff to finish. 我想发生的是,它只是等待内容完成。

con.run basically does an initial task and then a con.send. con.run基本上会执行初始任务,然后进行协商。

con.send basically runs this: con.send基本上运行以下命令:

private void sendToServer(byte[] message, int length, byte[]header) {

    byte[]payload = outrc4.encrypt(message,false);
    byte[] data = new byte[header.length+payload.length];

    System.arraycopy(header,0,data,0,header.length);
    System.arraycopy(payload,0,data,header.length,payload.length);


    try {
        out.write(data);
    } catch (IOException e) {
        System.out.println("Error!");
    }
}

It just sends the packet to the server. 它只是将数据包发送到服务器。

From here, on the con.run I get multiple packets back. 从这里,在con.run上,我得到了多个数据包。 I can catch the ID of the packet and in the loop that receives and parses the packet I can add an if statement which checks if the loginDone packet is received. 我可以捕获数据包的ID,并在接收和解析数据包的循环中添加一个if语句,该语句检查是否已收到loginDone数据包。

void receive() {
    try {

        while (in.available() > -1) {

              int type = in.readUnsignedShort();
              int size = in.readUnsignedByte();
              size <<= 8;
              size |= in.readUnsignedByte();
              size <<= 8;
              size |= in.readUnsignedByte();
              int version = in.readUnsignedShort();

              byte array[] = new byte[7];
              array[0] = (byte)((type >>> 8) & 0xFF);
              array[1] = (byte)(type & 0xFF);
              array[2] = (byte)((size >>> 16) & 0xFF);
              array[3] = (byte)((size >>> 8) & 0xFF);
              array[4] = (byte)(size & 0xFF);
              array[5] = (byte)((version >>> 8) & 0xFF);
              array[6] = (byte)(version & 0xFF);

              final byte[] reply = new byte[size];

             in.readFully(reply,0,size);

             byte[] data = new byte[array.length + reply.length];
             System.arraycopy(array, 0, data, 0, array.length);
             System.arraycopy(reply, 0, data, array.length, reply.length);
             byte[] decryptedPayload = inrc4.encrypt(reply,false);

            if(type == 20000){
                updateKeys(decryptedPayload);
            }

            if(type == 24411){
            //this one means that the 1st packet that uses con.run is done

                System.out.println("Logged In!");
            }

            if(type == 24334){
            //this one means that the 2nd packet that uses con.send is done 

                InputStream myis = new ByteArrayInputStream(decryptedPayload);
                new Avatar(myis);
                t.interrupt();
            }

        }


    } catch (Exception e) {}

}

Take not of these comments: //this one means that the 2nd packet that uses con.send is done and //this one means that the 1st packet that uses con.run is done 不接受这些注释://这表示使用con.send的第二个数据包已完成,//这表示使用con.run的第一个数据包已完成

This is as far as I have got. 据我所知。 Does anyone have any idea on what I should do from here? 有谁知道我应该从这里做什么?

If your server and client are in the same java process, use a CountDownLatch to do that, or thread.join() . 如果您的服务器和客户端在同一个Java进程中,请使用CountDownLatchthread.join() If they are different machines, read the EDIT part. 如果它们是不同的机器,请阅读EDIT部分。

class Foo extends Thread {

    CountDownLatch latch;

    public Foo(CountDownLatch latch) {
        this.latch = latch;
    }
    @Override
    public synchronized void start() {

        try {
            sleep(1000);
            latch.countDown(); // in every call latch decrease one, when it    reach to zero, every thread that is waiting the latch will continue.
sleep(100);
        } catch (InterruptedException e) {

        }
    }
}    
class FooBar {

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch latch = new CountDownLatch(1);

        new Foo(latch).start();

        latch.await(); // wait latch reach to zero. BE CAREFUL, IT'S NOT WAIT(),
                        // IT'S AWAIT()   
        System.out.println("done");
    }
}

EDIT I will keep the code above for the purposes of simplicity. 编辑为了简单起见,我将保留上面的代码。 I think it's very self-explanatory, could help the others. 我认为这很不言自明,可以帮助其他人。

Ok, if you want to wait until receive() method is completely, you need to develop a way that the server can say to the client that method is completed, or you can develop a way that your client keeps checking a some state in the server, like isTaskCompleted() . 好的,如果您要等到receive()方法完全完成,则需要开发一种方法,使服务器可以对客户端说该方法已完成,或者可以开发一种方法,使您的客户端不断检查客户端中的某些状态。服务器,例如isTaskCompleted() I don't know how dificult is your situation to make the server send a packet to the client. 我不知道您的情况如何使服务器向客户端发送数据包。 I will describe basically two approaches to this situation, I will use others name of class and variables, so try to adapt to your code. 我将基本上描述两种解决这种情况的方法,我将使用其他名称的类和变量,因此请尝试适应您的代码。

public class WaitServer extends Thread {

    synchronized void serverCompleted() {
        // when server completes
        notify();

    }

    @Override
    public synchronized void start() {

        try {
            wait(); // waits the server
        } catch (InterruptedException e) {                      

        }       
    }   
}
class ClientSide {

    void doSomething() {

        // ... some stuff ....      
        sendToServer();

        new WaitServer().join();

        // continues execution      
    }   
}

class ServerSide {
    void received() {

        // ... do some stuff .....

        if (someStuff) {            
            sendSignalToClient();

        }       
        // .. others stuff          
    }

    void sendSignalToClient() {     
        // here of course you need to send in the way that you are sending today, this is "pseudocode"
        client.serverCompleted()        
    }       
}

Another approach is to make your client checking the server until task is completed, simply create a Thread the send a verification of the job, if not completed sleep for some time. 另一种方法是让您的客户端检查服务器,直到任务完成为止,只需创建一个线程即可发送作业验证,如果一段时间未完成睡眠。 When you want to make a thread to wait another use join() . 当您想让一个线程等待另一个时,请使用join() If you want a thread to wait some part of the processing inside another, use CountDownLatch . 如果希望线程在另一个内部等待处理的某些部分,请使用CountDownLatch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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