您的位置:首页 > 理论基础 > 计算机网络

黑马程序员-用UDP编写网络聊天程序

2011-06-22 01:30 399 查看
/**
 * AWT Sample application
 *
 * @author
 * @version 1.00 11/06/21
 */
 
public class Chat {
   
    public static void main(String[] args) {
        // Create application frame.
        ChatFrame frame = new ChatFrame();
       
        // Show frame
        frame.setVisible(true);
        frame.setResizable(false);
    }
}
 
import java.awt.*;
import java.awt.event.*;
import java.net.*;
/**
 * Sample application using Frame.
 *
 * @author
 * @version 1.00 11/06/21
 */
public class ChatFrame extends Frame {
   
    /**
     * The constructor.
     */ 
    
    
    
    
     List lst=new List(6);
     TextField tfIP=new TextField(15);
     TextField tfData=new TextField(20);
    
     DatagramSocket ds=null;
    
     public ChatFrame() {
      Panel p=new Panel();
      add(p,"South");
      add(lst,"Center");
      
      try{
       ds=new DatagramSocket(3000);
      }catch(Exception e)
      {
       e.printStackTrace();
      }
      
      p.setLayout(new BorderLayout());
        p.add(tfIP,"West");
      p.add(tfData,"East");
         
      
      new Thread(new Runnable(){
        public void run(){
         
         byte[] buf=new byte[1024];
         DatagramPacket dp=new DatagramPacket(buf,1024);
         while(true){
          try{
         
          ds.receive(dp); 
          lst.add(new String(buf,0,dp.getLength())+
          " from "+dp.getAddress().getHostAddress()+":" +dp.getPort()
          ,0);
          }catch(Exception e){
           if (!ds.isClosed())
           e.printStackTrace();
          }
          
         }
         
        }
       }
       
       
       ).start();
      
      
      tfData.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
        byte [] buf;
        buf = tfData.getText().getBytes();
    try{
    
        DatagramPacket dp=new DatagramPacket(buf,buf.length,
        InetAddress.getByName(tfIP.getText()),3000);
        ds.send(dp);
        }catch(Exception er) {
         
         er.printStackTrace();
         
        }
        tfData.setText("");
        
       }
      }
       
       );
       
        setTitle("Chat");
        setSize(new Dimension(300, 300));
       
        // Add window listener.
        this.addWindowListener
        (
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    ChatFrame.this.windowClosed();
                }
            }
        ); 
    }
   
   
    /**
     * Shutdown procedure when run as an application.
     */
    protected void windowClosed() {
     
     // TODO: Check if it is safe to close the application
     
        // Exit application.
      
        ds.close();
        dispose();
        System.exit(0);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息