import java.applet.*;
import java.awt.*;

import java.net.*;
import java.io.*;

public class appcli extends Applet {

	String host = "kernighan.com";
	String port = "5194";
	TextField hostname = new TextField(40);
	TextField portnum = new TextField(10);
	TextField send = new TextField(60);
	TextArea recv = new TextArea(15,60);

public appcli()
{
	add(hostname);  hostname.setText(host);
	add(portnum);  portnum.setText(port);
	add(send);
	add(recv);
}

public boolean action(Event e, Object o)
{
	if (e.target == send) {
		recv.appendText("cli " + send.getText() + "\n");
		recv.appendText("srv " + echo(send.getText()) + "\n");
		return true;
	}
	return false;
}

String echo(String s)
{
	try {
		Socket client = new Socket(hostname.getText(), 
			Integer.parseInt(portnum.getText()));
		DataInputStream sin = 
			new DataInputStream(client.getInputStream());
		DataOutputStream sout = 
			new DataOutputStream(client.getOutputStream());

		sout.writeBytes(s);  // write to socket
		sout.writeByte('\n');
		sout.flush();
		String r = sin.readLine(); // read reply
		client.close();
		return r;
	} catch (IOException e) {
		return "IOException " + e;
	}
}

}
