1 public class Client extends JFrame implements Runnable{ 2 3 private JPanel jPanel= new JPanel(); 4 private JLabel jLabel1=new JLabel("姓名: "); 5 private JLabel jLabel2=new JLabel("端口: "); 6 private JTextField jTextField1=new JTextField(); 7 private JTextField jTextField2=new JTextField(); 8 private JTextArea jTextArea=new JTextArea(); 9 private JTextField jTextField3=new JTextField(); 10 private JButton jButton=new JButton("发送(S)"); 11 12 private JScrollPane jScrollPane=new JScrollPane(); 13 private BufferedReader bufferedReader; 14 private PrintWriter printWriter; 15 private Socket socket; 16 17 private static String title="劲爆聊天室"; 18 19 public Client(String port,String name){ 20 super(title+":"+name); 21 this.setSize(377,387); 22 this.add(jPanel); 23 jPanel.setLayout(null); 24 jTextArea.setEditable(false); 25 // 26 jPanel.add(jLabel1); 27 jLabel1.setBounds(10, 10, 60, 20); 28 jTextField1.setText(name); 29 jTextField1.setEditable(false); 30 jPanel.add(jTextField1); 31 jTextField1.setBounds(60, 10, 60, 21); 32 33 jPanel.add(jLabel2); 34 jLabel2.setBounds(125, 10, 60, 20); 35 jTextField2.setText(port); 36 jTextField2.setEditable(false); 37 jPanel.add(jTextField2); 38 jTextField2.setBounds(190, 10, 60, 21);; 39 40 jPanel.add(jTextField3); 41 jTextField3.setBounds(10, 270, 320, 21); 42 43 jTextArea.setColumns(20); 44 jTextArea.setRows(5); 45 46 jTextArea.setEditable(false); 47 jScrollPane.setViewportView(jTextArea); 48 jPanel.add(jScrollPane); 49 jScrollPane.setBounds(10, 42, 320, 220); 50 51 jPanel.add(jButton); 52 jButton.setBounds(250, 300, 80, 22); 53 jButton.addActionListener(new ActionListener() { 54 55 @Override 56 public void actionPerformed(ActionEvent e) { 57 // TODO Auto-generated method stub 58 if(e.getSource()==jButton){ 59 printWriter.println(jTextField1.getText()+": "+jTextField3.getText()); 60 jTextField3.setText(""); 61 } 62 } 63 }); 64 //Jtextfield不好控制啊。。。。 65 /* jTextField3.addActionListener(new ActionListener() { 66 67 @Override 68 public void actionPerformed(ActionEvent e) { 69 // TODO Auto-generated method stub 70 printWriter.println(jTextField1.getText()+":"+jTextField3.getText()); 71 jTextField3.setText(""); 72 } 73 });*/ 74 getSocket(); 75 } 76 @Override 77 public void run(){ 78 while(true) 79 { 80 try { 81 jTextArea.append(bufferedReader.readLine()+" "); 82 83 } catch (Exception e) { 84 // TODO: handle exception 85 e.printStackTrace(); 86 } 87 } 88 } 89 90 public void getSocket(){ 91 jTextArea.append("正在与劲爆聊天室进行连接..."+" "); 92 try { 93 socket=new Socket("127.0.0.1",PortNumber.PORT.getNumber()); 94 jTextArea.append("劲爆聊天开始..."+" "); 95 bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream())); 96 printWriter=new PrintWriter(socket.getOutputStream(),true); 97 new Thread(this).start(); 98 } catch (Exception e) { 99 // TODO: handle exception 100 e.printStackTrace(); 101 } 102 } 103 104 }
考虑到多客户端,此处用到了多线程。Socket确实有意思....
非常感叹T公司如果把一个IM软件,做到亿级用户量,如何解决并发,如何解决Server的及时回应,如何完成数据存储...
想不出来了...