package my;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class MyTest
{
private Frame f;
private TextArea t1,t2;
private Button b1,b2;
private DatagramSocket d1,d2;
public MyTest() throws Exception
{
init();
}
public void init()throws Exception
{
f=new Frame("我的窗口");
f.setBounds(300,200,540,540);
f.setLayout(new FlowLayout());
t1=new TextArea(13,67);
t2=new TextArea(13,67);
b1=new Button("关闭");
b2=new Button("发送");
f.add(t1);
f.add(t2);
f.add(b1);
f.add(b2);
myEvent();
f.setVisible(true);
d1=new DatagramSocket();
d2=new DatagramSocket(10001);
new Thread(new Runnable()
{
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName());
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
try
{
d2.receive(dp);
} catch (IOException e)
{
e.printStackTrace();
}
t1.append("来自刘汉文"+dp.getAddress().getHostAddress()+"\r\n");
t1.append(new String(dp.getData(),0,dp.getLength())+"\r\n");
}
}
}).start();
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
//System.out.println(Thread.currentThread().getName());
show();
} catch (Exception e1)
{
e1.printStackTrace();
}
}
});
t2.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
try
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
show();
} catch (Exception e1)
{
e1.printStackTrace();
}
}
});
}
public void show()
{
String s=t2.getText();
t1.append("发送刘汉文"+"\r\n"+s+"\r\n");
System.out.println(Thread.currentThread().getName()+"---");
byte[] buf=s.getBytes();
DatagramPacket dp = null;
try
{
dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10001);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
try
{
d1.send(dp);
}
catch (IOException e)
{
e.printStackTrace();
}
t2.setText("");
}
public static void main(String[] args) throws Exception
{
new MyTest();
}
}
|