簡體   English   中英

Java如何等待命令完成?

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

我有以下腳本:

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

請注意以下內容?

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

和這個:

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

所以這會暫停我的腳本一段時間,但是我不希望這樣,因為腳本可能會花費更長或更短的時間。 那會浪費一些時間D:

我想發生的是,它只是等待內容完成。

con.run基本上會執行初始任務,然后進行協商。

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!");
    }
}

它只是將數據包發送到服務器。

從這里,在con.run上,我得到了多個數據包。 我可以捕獲數據包的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) {}

}

不接受這些注釋://這表示使用con.send的第二個數據包已完成,//這表示使用con.run的第一個數據包已完成

據我所知。 有誰知道我應該從這里做什么?

如果您的服務器和客戶端在同一個Java進程中,請使用CountDownLatchthread.join() 如果它們是不同的機器,請閱讀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");
    }
}

編輯為了簡單起見,我將保留上面的代碼。 我認為這很不言自明,可以幫助其他人。

好的,如果您要等到receive()方法完全完成,則需要開發一種方法,使服務器可以對客戶端說該方法已完成,或者可以開發一種方法,使您的客戶端不斷檢查客戶端中的某些狀態。服務器,例如isTaskCompleted() 我不知道您的情況如何使服務器向客戶端發送數據包。 我將基本上描述兩種解決這種情況的方法,我將使用其他名稱的類和變量,因此請嘗試適應您的代碼。

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()        
    }       
}

另一種方法是讓您的客戶端檢查服務器,直到任務完成為止,只需創建一個線程即可發送作業驗證,如果一段時間未完成睡眠。 當您想讓一個線程等待另一個時,請使用join() 如果希望線程在另一個內部等待處理的某些部分,請使用CountDownLatch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM