public class ConnectDemo extends Thread
{
    public static void main(String args[]) throws Exception
    {
	SimpleCapi[] capi = new SimpleCapi[2];
	capi[0] = new SimpleCapi("127.0.0.1", 7347);
	capi[1] = new SimpleCapi("127.0.0.1", 7347);

	capi[0].call_nonblock("123456"); //call first person
	capi[1].call_nonblock("789012"); //call second person

	boolean[] done = new boolean[2];
	done[0] = done[1] = false;
	int nr=0;

	/* loop until both picked up, or we determined we can't
	   call one of the two for whatever reason (e.g. line busy) */
	while(!done[0] || !done[1])
	{
	    if(!done[nr]) {
		CapiEvent event;
		event = capi[nr].listen(1);
		if(event.type == SimpleCapi.CAPI_EVENT_CONNECTED)
		    break;
		if(event.type == SimpleCapi.CAPI_EVENT_HANGUP) {
		    /* rejected, busy, ... */
		    capi[0].close();
		    capi[1].close();
		    return;
		}
	    }
	    nr^=1;
	}

	/* connect them */
	capi[0].connect(capi[0],capi[1]);

	/* Wait until either of the two hangs up */
	while(true) {
	    CapiEvent event0 = capi[0].listen(1);
	    if (event0.type == SimpleCapi.CAPI_EVENT_HANGUP)
		break;
	    CapiEvent event1 = capi[1].listen(1);
	    if (event0.type == SimpleCapi.CAPI_EVENT_HANGUP)
		break;
	}

	/* Close both lines. This will also hang up on the remaining
	   person */
	capi[0].close();
	capi[1].close();
    }
}
