【Java开源代码栏目提醒】:网学会员在Java开源代码频道为大家收集整理了UDPGet.java提供大家参考,希望对大家有所帮助!
/*源代码清单8-4*/
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class UDPGet extends Frame implements ActionListener
{
TextArea textArea1 = new TextArea();
Button button1 = new Button();
public static void main(String[] args)
{
UDPGet get=new UDPGet();
get.setLocation(100,100);
get.setSize(300,200);
get.show();
get.waitForData();
}
public UDPGet()
{
try
{
jbInit();
}
catch (Exception e)
{
e.printStackTrace();
}
}
void waitForData()
{
try
{
byte[] buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
DatagramSocket socket=new DatagramSocket(9999);
while(true)
{
socket.receive(packet);
String s=new String(buffer,0,0,packet.getLength());
textArea1.append(s+"\n");
packet=new DatagramPacket(buffer,buffer.length);
}
}catch(Exception e)
{
}
}
private void jbInit() throws Exception
{
this.setTitle("接收数据报");
textArea1.setText("");
button1.setLabel("退出 ");
this.add(textArea1, BorderLayout.CENTER);
this.add(button1, BorderLayout.SOUTH);
button1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Component com=(Component)e.getSource();
if(com.equals(button1))
System.exit(0);
}
}