UPD聊天程序.

    技术2024-06-13  70

     

     

    import java.awt.BorderLayout;import java.awt.Frame;import java.awt.List;import java.awt.Panel;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;

    public class Message {

     /**  * @param args  */  DatagramSocket ds = null;  public Message(){  try{   ds = new DatagramSocket(3000);  }catch(Exception e){   e.printStackTrace();  } }  public static void main(String[] args) {    final Message m = new Message();  //构造界面  final Frame f = new Frame();  final List l = new List(6);  final TextField tfip = new TextField(15);  final TextField tfmeg  = new TextField(20);  f.add(l,"Center");  Panel p = new Panel();  f.add(p,"South");  p.setLayout(new BorderLayout());  p.add(tfip,"West");  p.add(tfmeg,"East");  f.setSize(300, 400);  f.setResizable(false);  f.setVisible(true);    //分出一个线程,单独执行接收方法.因为receive方法能够阻碍程序,只有接收到程序才能继续运行.  new Thread(new Runnable(){   public void run() {    //初始化接受的内存缓冲区    byte[] buf = new byte[1024];    DatagramPacket dp = new DatagramPacket(buf,1024);    while(true){     try {      m.ds.receive(dp);      String s = new String(dp.getData(),0,dp.getLength());      s += "--"+dp.getAddress().getHostAddress();      l.add(s,0);     } catch (IOException e) {      //如果Socket已经关闭,则不打印异常.      if(m.ds.isClosed()){             }else{       e.printStackTrace();      }           }    }       }     }).start();      //关闭界面监听  f.addWindowListener( new WindowAdapter(){   public void windowClosing(WindowEvent e){    m.ds.close();    f.dispose();    System.exit(0);   }  });      //按回城键发送数据.  tfmeg.addActionListener( new ActionListener(){   public void actionPerformed(ActionEvent e) {    String ip = tfip.getText();    String message = tfmeg.getText();    try {     DatagramPacket dp = new DatagramPacket(message.getBytes(),message.getBytes().length,InetAddress.getByName(ip),3000);     m.ds.send(dp);     tfmeg.setText("");    } catch (Exception e1) {     // TODO Auto-generated catch block     e1.printStackTrace();    }   }     }); }

    }

     

     

    //在ip地址栏输入:127.0.0.1 ,可以接收到信息,因为127.0.0.1是本地ip,不经过网卡.

    //输入本地ip可以也接收到信息.

    //输入广播地址的ip,也可以收到信息.

    //关于广播地址请看

    http://baike.baidu.com/view/473043.htm

     

     

     

    最新回复(0)