// How to use Sockets to create Client programs in Java import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class client extends JFrame { Socket sock; DataInputStream sis; DataOutputStream sos; JTextArea display; JButton Stopcom; JButton Sendcom; JTextField Comtext; public client () { super("Client Program:"); display = new JTextArea(5, 25); display.setLineWrap(true); display.setEditable(false); display.setBackground(Color.green); JScrollPane jsp = new JScrollPane(display); jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); Stopcom = new JButton("Stop"); Sendcom = new JButton("Send"); Comtext = new JTextField(15); Panel p = new Panel(); p.setLayout(new FlowLayout()); p.add(Stopcom); p.add(Sendcom); Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(Comtext, BorderLayout.NORTH); c.add(jsp, BorderLayout.CENTER); c.add(p, BorderLayout.SOUTH); setSize(300,150); setLocation(300,300); setVisible(true); EventHandler ev = new EventHandler(this); Stopcom.addActionListener(ev); Sendcom.addActionListener(ev); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void runClient() { try { sock = new Socket(InetAddress.getLocalHost(), 5500); display.append("Contacted server at 5500\n"); sis = new DataInputStream(sock.getInputStream()); sos = new DataOutputStream(sock.getOutputStream()); Sendcom.setEnabled(true); String reply = sis.readUTF(); display.append( reply + "\n"); if (reply.equalsIgnoreCase("Refused")) { display.setBackground(Color.red); Sendcom.setEnabled(false); } } catch (IOException e) { e.printStackTrace(); } } public static void main (String args[]) { client c = new client(); c.runClient(); } } class EventHandler implements ActionListener { client c; EventHandler (client x) { c = x; } public void actionPerformed(ActionEvent a) { try { if (a.getSource() == c.Stopcom) { if (c.Sendcom.isEnabled()) // indicates valid client { c.sos.writeUTF("STOP"); c.display.append(c.sis.readUTF() + "\n"); c.sock.close(); } System.exit(1); } if (a.getSource() == c.Sendcom) { c.sos.writeUTF(c.Comtext.getText()); c.display.append( c.sis.readUTF() + c.sis.readInt() + "\n"); } } catch (IOException i) { c.display.append("Error: " + i.toString() + "\n"); System.exit(1); } } }