UDPSend.java:import java.net.*;
import java.awt.*;
import java.awt.event.*;public class UDPSend extends Frame implements ActionListener
{
TextArea textField1 = new TextArea();
Button button1 = new Button();
Button button2 = new Button();

public UDPSend()
{
try
{
jbInit();
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent e)
{
Component com = (Component)e.getSource();
if (com.equals(button1))
{
sendData();
}
else if (com.equals(button2))
{
System.exit(0);
}
else
{
sendData();
}
}

void sendData()
{
try
{
String msg = textField1.getText();
if (msg.equals(""))
{
return;
}
textField1.setText("");
InetAddress address = InetAddress.getByName("127.0.0.1");
byte[] message = msg.getBytes("GBK");
int len = message.length;
String s = new String(message);
DatagramPacket packet = new DatagramPacket(message, len, address, 9999);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
}
catch (Exception e)
{
}
}

private void jbInit()
throws Exception
{
this.setTitle("Send Datagram");
button1.setLabel("Send");
button2.setLabel("Exit");
this.add(textField1, BorderLayout.NORTH);
this.add(button1, BorderLayout.CENTER);
this.add(button2, BorderLayout.SOUTH);
button1.addActionListener(this);
button2.addActionListener(this);
}

public static void main(String[] args)
{
UDPSend send = new UDPSend();
send.setLocation(400, 400);
send.setSize(200, 120);
send.show();
}}
UDPGet.javaimport 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 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, packet.getLength());
textArea1.append(s + "\n");
packet = new DatagramPacket(buffer, buffer.length);
}
}
catch (Exception e)
{
}
}

private void jbInit()
throws Exception
{
this.setTitle("Receive Datagram");
textArea1.setText("");
button1.setLabel("Exit");
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);
}
}

public static void main(String[] args)
{
UDPGet get = new UDPGet();
get.setLocation(100, 100);
get.setSize(300, 200);
get.show();
get.waitForData();
}}开两个窗口,运行一下看吧。这个做得很简陋。后来我做了一个在局域网里面通过udp通讯聊天的东东,不过比这个大得多了。