Client端:
1 package mylab; 2 3 import java.awt.BorderLayout; 4 import java.awt.Dimension; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 import java.io.BufferedReader; 8 import java.io.IOException; 9 import java.io.InputStreamReader; 10 import java.io.PrintWriter; 11 import java.net.Socket; 12 13 import javax.swing.JButton; 14 import javax.swing.JFrame; 15 import javax.swing.JPanel; 16 import javax.swing.JScrollPane; 17 import javax.swing.JTextArea; 18 import javax.swing.ScrollPaneConstants; 19 20 public class Client extends JFrame implements ActionListener { 21 JTextArea input; 22 JTextArea output; 23 JButton close; 24 JButton send; 25 JScrollPane top = new JScrollPane(); 26 JPanel medium, bottom; 27 28 String inMessage, outMessage; 29 30 String s = null; 31 Socket mysocket; 32 BufferedReader br = null; 33 PrintWriter pw = null; 34 35 /** 36 * @param args 37 */ 38 public Client() { 39 super(); 40 setTitle("客户端"); 41 setVisible(true); 42 setBounds(200, 150, 350, 400); 43 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 44 45 top = new JScrollPane(); 46 top.setPreferredSize(new Dimension(300, 200)); 47 top.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); 48 output = new JTextArea(6, 25); 49 top.setViewportView(output); 50 51 medium = new JPanel(); 52 medium.setPreferredSize(new Dimension(300, 120)); 53 input = new JTextArea(4, 27); 54 medium.add(input); 55 56 bottom = new JPanel(); 57 bottom.setPreferredSize(new Dimension(300, 60)); 58 close = new JButton("关闭"); 59 close.addActionListener(this); 60 send = new JButton("发送"); 61 send.addActionListener(this); 62 bottom.add(close); 63 bottom.add(send); 64 65 getContentPane().add(top, BorderLayout.NORTH); 66 getContentPane().add(medium, BorderLayout.CENTER); 67 getContentPane().add(bottom, BorderLayout.SOUTH); 68 } 69 70 public static void main(String[] args) { 71 // TODO Auto-generated method stub 72 Client client = new Client(); 73 client.run(); 74 } 75 76 public void run() { 77 78 try { 79 80 mysocket = new Socket("127.0.0.1", 2222); 81 br = new BufferedReader(new InputStreamReader( 82 mysocket.getInputStream())); 83 pw = new PrintWriter(mysocket.getOutputStream(), true); 84 while ((inMessage = br.readLine()) != null) { 85 output.append("服务器说:" + inMessage + "\n"); 86 } 87 88 } catch (Exception e) { 89 } 90 } 91 92 @Override 93 public void actionPerformed(ActionEvent e) { 94 // TODO Auto-generated method stub 95 if (close.hasFocus()) { 96 try { 97 mysocket.close(); 98 System.out.println("客户端已关闭"); 99 } catch (IOException e1) { 100 // TODO Auto-generated catch block 101 e1.printStackTrace(); 102 } 103 } 104 if (send.hasFocus()) { 105 outMessage = input.getText(); 106 input.setText(null); 107 output.append("客户端说:" + outMessage + "\n"); 108 pw.println(outMessage); 109 pw.flush(); 110 } 111 } 112 113 }