public class ChatClient { private SocketChannel sc = null; private String name = null; private Frame f; private TextArea ta; private TextField tf; private boolean runnable = true;
public static void main(String[] args){ ChatClient cc = new ChatClient(); cc.createUI(); cc.inputName(); cc.connect(); new ReceiveThread(cc,cc.getTextArea()).start(); } public SocketChannel getSc(){ return sc; } public void setName(String name){ this.name = name; } public TextArea getTextArea(){ return ta; } public TextField getTextField(){ return tf; } public boolean getRunnable(){ return runnable; } public void stop(){ runnable = false; }
public void shutDown(){ try{ sc.write(ByteBuffer.wrap("bye".getBytes("GBK"))); ta.append("Exit in 5 seconds!"); this.stop(); Thread.sleep(5000); sc.close(); }catch(Exception e){ e.printStackTrace(); } System.exit(0); }
public void createUI(){ f = new Frame("Client"); ta = new TextArea(); ta.setEditable(false); tf = new TextField(); Button send = new Button("Send"); Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(tf,"Center"); p.add(send,"East"); f.add(ta,"Center"); f.add(p,"South"); MyClientListener listener = new MyClientListener(this); send.addActionListener(listener); tf.addActionListener(listener); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ ChatClient.this.shutDown(); } }); f.setSize(400,400); f.setLocation(600,0); f.setVisible(true); tf.requestFocus(); }
public boolean connect(){ try{ sc = SocketChannel.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1",8888); sc.connect(isa); sc.configureBlocking(false); sc.write(ByteBuffer.wrap(name.getBytes("GBK"))); }catch(Exception e){ e.printStackTrace(); } return true; }
public void inputName(){ String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:"); this.setName(name); f.setTitle(name); } }