package cn.itcast.day1;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MyQQ {
/**
* @param args
*/
private Frame f;
private TextArea ta1,ta2;
private Button cancelBut,sendBut;
MyQQ()
{
init();
}
public void init()
{
f= new Frame("my qq");
ta1 = new TextArea(12,65);
ta2 = new TextArea(12,65);
cancelBut = new Button("取消");
sendBut = new Button("发送");
f.setBounds(200, 100, 500, 550);
f.setLayout(new FlowLayout());
f.add(ta1);
f.add(ta2);
f.add(cancelBut);
f.add(sendBut);
myEvent();
f.setVisible(true);
}
public void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
cancelBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
f.setVisible(false);
}
});
sendBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String text = ta2.getText();
try {
send(text);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//receive();
receive();
}
});
}
public void send(final String str) throws Exception
{
new Thread(new Runnable(){
public void run()
{
try
{
DatagramSocket ds = new DatagramSocket();
byte[] buf =str.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.23"),10000);
ds.send(dp);
}
catch(Exception e)
{
System.out.println("发送失败");
}
}
}).start();
}
public void receive()
{
new Thread(new Runnable(){
public void run()
{
try
{
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData());
int port = dp.getPort();
ta1.setText(ip+":"+data);
}
catch(Exception e)
{
System.out.println("接收失败");
}
}
}).start();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyQQ();
}
}
|
|