package project;
import java.lang.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class UDPchat extends Frame implements Runnable{
Label L1,L2;
TextField text1,text2;
Button B1;
List list1;
public UDPchat()
{
this.setLayout(null);
//====================================================================
L1=new Label("对方IP:");
L1.setBounds(10,30,60,30);
this.add(L1);                                 //===========//
L2=new Label("发言:");                        //=   工     =//
L2.setBounds(10,70,60,30);                    //=   作     =//
this.add(L2);                                 //=   区     =//
text1=new TextField("127.0.0.1",20);          //=   布     =//
text1.setBounds(75,30,200,30);                //=   局     =//
this.add(text1);                              //=         =//
text2=new TextField();                        //=         =//
text2.setBounds(75,70,320,30);                //===========//
this.add(text2);
B1=new Button("send");
B1.setBounds(400,70,60,30);
B1.addMouseListener(new myMouseListener());//添加鼠标监听事件
this.add(B1);
list1=new List(15);
list1.setBounds(15,110,450,300);
this.add(list1);
//=====================================================================
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
this.setTitle("使用UDP的网络聊天程序");
this.setBounds(100,100,480,430);
this.setVisible(true);
}
public void run()
{    //接收数据
while(true)
{
byte[] buf=new byte[100];
try
{
DatagramSocket DS=new DatagramSocket(2222);
DatagramPacket DP=new DatagramPacket(buf,buf.length);
DS.receive(DP);
list1.add("来自"+DP.getAddress().getHostAddress()+":"+DP.getPort()+">"+new String(buf).trim());
DS.close();
Thread.sleep(200);
}
catch(Exception excep){}
}

}
class myMouseListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
String msg=text2.getText().trim();
String ipStr=text1.getText().trim();
try
{
DatagramSocket DS=new DatagramSocket();
DatagramPacket DP=new DatagramPacket(msg.getBytes(),msg.getBytes().length,InetAddress.getByName(ipStr),2222);
DS.close();
}catch(Exception excep){}
}
}
public static void main(String arg[])
{
UDPchat Form1=new UDPchat();
Thread threadObj=new Thread(Form1);
threadObj.start();
}}