// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package socket.plain.binary.modern;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SocketChannel;

public class Client {
    private static final String HOST = "localhost";
    private static final int PORT = 12345;
    public static void main(String[] args) {
        try {
            // open connection
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress(HOST, PORT));
            System.out.println("(connected)");
            ByteBuffer bb;
            // send a and b
            int a = 123;
            int b = 456;
            bb = ByteBuffer.allocate(8);
            bb.order(ByteOrder.BIG_ENDIAN);
            bb.putInt(a);
            bb.putInt(b);
            bb.rewind();
            sc.write(bb);
            // receive c and print
            bb = ByteBuffer.allocate(4);
            while(bb.hasRemaining() && sc.read(bb) > 0);
            bb.rewind();
            bb.order(ByteOrder.BIG_ENDIAN);
            int c = bb.getInt();
            System.out.println(c);
            // send v
            String v = "ABC";
            byte[] vb = v.getBytes("UTF-8");
            bb = ByteBuffer.allocate(1 + vb.length);
            bb.put((byte)vb.length);
            bb.put(vb);
            bb.rewind();
            sc.write(bb);
            // receive v2 and print
            bb = ByteBuffer.allocate(1);
            sc.read(bb);
            bb.rewind();
            int buflen = bb.get();
            bb = ByteBuffer.allocate(buflen);
            while(bb.hasRemaining() && sc.read(bb) > 0);
            bb.rewind();
            byte[] buf = new byte[buflen];
            bb.get(buf);
            String v2 = new String(buf, "UTF-8");
            System.out.println(v2);
            // close connection
            sc.close();
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }
}
