// 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.traditional;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {
    private static final String HOST = "localhost";
    private static final int PORT = 12345;
    public static void main(String[] args) {
        try {
            // open connection
            Socket s = new Socket(HOST, PORT);
            // get streams
            DataInputStream dis = new DataInputStream(s.getInputStream());
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            System.out.println("(connected)");
            // send a and b
            int a = 123;
            int b = 456;
            dos.writeInt(a);
            dos.writeInt(b);
            dos.flush();
            // receive c and print
            int c = dis.readInt();
            System.out.println(c);
            // send v
            String v = "ABC";
            byte[] vb = v.getBytes("UTF-8");
            dos.writeByte(vb.length);
            dos.write(vb);
            dos.flush();
            // receive v2 and print
            int buflen = dis.readByte();
            byte[] buf = new byte[buflen];
            int ix = 0;
            while(ix < buf.length) {
                ix += dis.read(buf, ix, buf.length - ix);
            }
            String v2 = new String(buf, "UTF-8");
            System.out.println(v2);
            // close connection
            dis.close();
            dos.close();
            s.close();
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }
}
