// Test 3
   
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;

public class Test3 extends Applet
{
	private Button writeButton;
	private Button clearButton;
	private TextField textInput;

	private Panel buttonPanel;
	private Panel inputPanel;

	public void init()
	{
		clearButton = new Button("Clear");
		writeButton = new Button("Write");
		buttonPanel = new Panel();
		buttonPanel.add(clearButton);
		buttonPanel.add(writeButton);

		textInput = new TextField("", 10);
		inputPanel = new Panel();
		inputPanel.add(textInput);

		setLayout(new BorderLayout());
		add("North", buttonPanel);
		add("Center", inputPanel);
	}

	public boolean action(Event e, Object arg)
	{
		if (e.target == clearButton)
			textInput.setText("");
		else if (e.target == writeButton)
			getAppletContext().showStatus(writeText(textInput.getText()));
		return true;
	}

	public String writeText(String text)
	{
		Socket s = null;
		String status;
		int textLength = text.length();
		try
		{
			s = new Socket(getParameter("Server"), 80);
			DataInputStream in = new DataInputStream(s.getInputStream());
			DataOutputStream out = new DataOutputStream(s.getOutputStream());
			out.writeBytes("POST /cgi-bin/bprentice/Test3.pl HTTP/1.0\n");
			out.writeBytes("Content-type: text/plain\n");
			out.writeBytes("Content-length: " + textLength + "\n\n");
			for (int i = 0; i < textLength; i++)
				out.writeByte(text.charAt(i));
			String line;
			do
				line = in.readLine();
			while (! line.equals(""));
			line = in.readLine();
			if (line.startsWith("Error:"))
				status = line;
			else
				status = "text written (" + textLength + " bytes)";
		}
		catch (Exception e1)
		{
			status = "Error writing text: " + e1;
		}
		finally
		{
			try
			{
				if (s != null)
					s.close();
			}
			catch (Exception e2)
			{
			}
		}
		return status;
	}
}

