import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Sender_Window extends JFrame
{
    JButton Send;
    JTextField message;
    ObjectOutputStream o_stream;
    Socket send_sock;
    ServerSocket server_sock;

    Sender_Window ( String hostname, int port )
    {
	setTitle("Sender");
	setSize( 400, 300 );

	Container cp = getContentPane();
	ButtonHandler bh = new ButtonHandler();
	addWindowListener( new windowHandler() );

	Send = new JButton( "Send" );
	Send.addActionListener( bh );
	cp.add( Send, "East" );
	
	message = new JTextField();
	cp.add ( message, "South");

	setVisible( true );

	openConnection( hostname, port);
    }

    class ButtonHandler implements ActionListener
    {
	public void actionPerformed ( ActionEvent e )
	{
	    Object ob = e.getSource();

	    if ( ob == Send ) {
		try {
		    o_stream.writeObject( message.getText() );
		} catch ( IOException f ) {
		    System.out.println( f.getMessage() );
		}
	    }
	}
    }

    private void openConnection( String hostname, int port )
    {
	
	try {
	    send_sock = new Socket( hostname, port );
	    o_stream = new ObjectOutputStream ( send_sock.getOutputStream() );
	    //The object output stream does not use autoflush
	} catch ( UnknownHostException e ) {
	    System.out.println( e.getMessage() );
	} catch ( IOException e ) {
	    System.out.println ( e.getMessage() );
	}
    }
    

    private void closeConnection( ) throws IOException
    {
	o_stream.close();
    }

    class windowHandler extends WindowAdapter
    {
	public void windowClosing( WindowEvent e ) 
	{
	    try {
		closeConnection();
	    } catch (IOException i ) {
		System.out.println( i.getMessage() );
	    } finally {
		System.exit(0);
	    }
	}
    }
}



public class Sender
{
    public static void main ( String []args )
    {
	String hostname =null;

	if ( args.length < 2 ) {
	    System.out.println( "Usage: Sender targethostname port ");
	    System.exit(0);
	}

	Sender_Window cm = new Sender_Window( args[0], Integer.parseInt( args[1] ) );

    }
}

