黑马程序员技术交流社区
标题:
用于接收和发送消息UDP & AWT
[打印本页]
作者:
许云龙
时间:
2013-8-18 08:53
标题:
用于接收和发送消息UDP & AWT
/*
需求:定义一个程序,用于接收和发送消息
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
//发送端
class Send implements Runnable
{
private String text;
public Send(String text)
{
this.text = text;
}
public void run()
{
try
{
DatagramSocket ds = new DatagramSocket(7777);
byte [] buf = text.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10004);
ds.send(dp);
ds.close();
}
catch(Exception e)
{
throw new RuntimeException("发送失败");
}
}
}
//接收端
class Rece implements Runnable
{
private TextArea receArea;
public Rece(TextArea receArea)
{
this.receArea = receArea;
}
public void run()
{
try
{
DatagramSocket ds = new DatagramSocket(10005);
while(true)
{
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(),0,dp.getLength());
receArea.append("-----_"+ip+"说:\r\n"+data+"\r\n");
}
}
catch(Exception e)
{
throw new RuntimeException("接收失败");
}
}
}
//窗体
class myFrame
{
private Frame f;
private Button but;
private TextArea sendArea,receArea;
public myFrame()
{
init();
}
public void init()
{
f = new Frame("聊天窗口");
but = new Button("发送");
receArea = new TextArea(15,76);
sendArea = new TextArea(12,70);
f.setBounds(200,100,600,500);
myEvent();
f.setLayout(new FlowLayout());
f.add(receArea);
f.add(sendArea);
f.add(but);
f.setVisible(true);
new Thread(new Rece(receArea)).start();
}
//监听器
public void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
//按钮 -- 活动监听器
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String text = sendArea.getText();
Thread sendThread = new Thread(new Send(text));
sendThread.start();
//sendThread.interrupt();
sendArea.setText("");
}
});
//下文本区 -- 键盘监听器
sendArea.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.isControlDown() && e.getKeyCode()==e.VK_ENTER)
{
String text = sendArea.getText();
Thread sendThread = new Thread(new Send(text));
sendThread.start();
sendThread.interrupt();
sendArea.setText("");
}
}
});
}
}
class UdpAndAwt
{
public static void main(String[] args)
{
new myFrame();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2