[java] view plaincopyprint?
// Fig. 18.5: Client.java
// Client that reads and displays information sent from a Server.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class ClientGUI extends JFrame
{
private JTextArea displayArea;
private JTextField enterField;
private String request="";
public ClientGUI()
{
super( "Client" );
Container container = getContentPane();
displayArea = new JTextArea();
enterField=new JTextField();
container.add(enterField,BorderLayout.NORTH);
container.add( new JScrollPane( displayArea ),
BorderLayout.CENTER );
setSize( 300, 150 );
setAlwaysOnTop(true);
setVisible( true );
Handler handler=new Handler();
enterField.addActionListener(handler);
}
private class Handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
setRequest(e.getActionCommand());
setField("");
}
}
public JTextField getGUIField()
{
return enterField;
}
public JTextArea getGUIArea()
{
return displayArea;
}
public void setRequest(String s)
{
request=s;
}
public String getRequest()
{
return request;
}
public void setField(String s)
{
enterField.setText(s);
}
public void appendArea(String s)
{
displayArea.append(s+"\n");
}
public void setArea(String s)
{
displayArea.setText(s);
}
} // end class Client
import java.io.*;
import java.net.*;
public class Client extends Thread
{
private ClientGUI g;
private String time="";
private Socket client;
private ObjectInputStream in;
private ObjectOutputStream out;
public Client( ClientGUI gui)
{
super( "Client" );
g=gui;
g.setRequest("get");
}
public void run()
{
try
{
Thread.sleep(500);
client = new Socket( InetAddress.getLocalHost(), 24680 );
out=new ObjectOutputStream(client.getOutputStream());
in=new ObjectInputStream(client.getInputStream());
Thread.sleep(500);
while(true)
{
Thread.sleep(500);
if(!g.getRequest().equals(""))
{
out.writeObject(g.getRequest());
out.flush();
Thread.sleep(500);
if(g.getRequest().equals("get"))
{
time=in.readObject().toString();
g.setArea(time);
}
else
if(g.getRequest().equals("close"))
{
out.close();
in.close();
client.close();
}
else
continue;
}
}
}
catch ( IOException ioException )
{
ioException.printStackTrace();
}
catch(InterruptedException e)
{
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
} // end class Client
// Fig. 18.5: Client.java
// Client that reads and displays information sent from a Server.
import javax.swing.*;
public class ClientRun
{
//private String request;
public static void main( String args[] )
{
ClientGUI app;
app = new ClientGUI( );
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Client client=new Client(app);
client.start();
}
} // end class Client