0

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:

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.send basically runs this:

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. 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.

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

This is as far as I have got. Does anyone have any idea on what I should do from here?

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • this is too much code to sift through, but I think you're looking for wait() notify() https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html – WalterM Oct 09 '15 at 19:49

1 Answers1

1

If your server and client are in the same java process, use a CountDownLatch to do that, or thread.join(). If they are different machines, read the EDIT part.

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(). 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(). If you want a thread to wait some part of the processing inside another, use CountDownLatch.

Johnny Willer
  • 3,717
  • 3
  • 27
  • 51
  • @ShivamPaw you want wait until receive() is completed or just until send()? – Johnny Willer Oct 09 '15 at 19:47
  • Please see if this helps : http://stackoverflow.com/questions/15956231/what-does-this-thread-join-code-mean –  Oct 09 '15 at 19:48
  • So each time something comes in through the inputstream I can check the ID of the packet. if packet x comes in then i can continue from where i send the first packet to the server (con.run) when pakcet y comes in from con.send I can continue to parsing the josn bit –  Oct 09 '15 at 19:52
  • @ShivamPaw one question, are your 'server' and 'client' in the same program/java process? or they are different machines? – Johnny Willer Oct 09 '15 at 20:16
  • @ShivamPaw ok, take a look at my answer again. – Johnny Willer Oct 09 '15 at 20:43