//发送消息类
Message.java
import java.io.Serializable;
public class Message implements Serializable{
private String msg;
private String id;
private String destid;
public Message(String msg, String id, String destid) {
this.msg = msg;
this.id = id;
this.destid = destid;
}
//获得消息内容
public String getMessage() {
return msg;
}
//获得发送方的ip
public String getID() {
return id;
}
//获得接受方的ip
public String getDestID() {
return destid;
}
}
 
//接受方
Receiver.java
import java.net.*;
import java.io.*;
public class Receiver extends Thread {
private Message msg;
private DatagramPacket packet;
private DatagramSocket socket;
private byte[] recvBuf = new byte[500];
public Receiver() {
try{
//创建udp包以接受数据。
packet = new DatagramPacke(recvBuf,recvBuf.length);
//创建接受方的udp端口以接收数据
socket = new DatagramSocket(7002);
}
catch(Exception e){}
}
public void run() {
try {
while(true){
//接受数据
socket.receive(packet);
ByteArrayInputStream byteStream = new
ByteArrayInputStream(recvBuf);
ObjectInputStream is = new ObjectInputStream(new
BufferedInputStream(byteStram));
Object o = is.readObject();
msg = (Message)o;
is.close();
System.out.println(msg.getMessage());
}
}
catch(Throwable t) {
t.printStackTrace();
}
}
}

//发送方
Sender.java
import java.net.*;
import java.io.*;
public class Sender extends Thread {
private Message msg;
private DatagramSocket socket;
private DatagramPacket packet;
public Sender(Message msg) {
try {
this.msg = msg;
//获得目的方的ip地址
String destID = msg.getDestID();
//获得将要发送的消息内容
String destID = msg.getDestIDString message = msg.getMessage();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(500);
ObjectOutputStream os = new ObjectOutputStream(new
BufferedOutputStream(byteStream));
os.writeObject(msg);
os.flush();
byte[] sendBuf = byteStream.toByteArray();
//创建udp数据包以发送数据
packet = new DatagramPacket(sendBuf,sendBuf.length,
InetAddress.getByName(destID),7002);
//创建发送udp套接字,指定套接字口。
socket = new DatagramSocket(7000);
os.close();
}
catch(Throwable t) {
t.printStackTrace();
}
}
public void run() {
try {
//发送消息
socket.send(packet);
//发送完毕关闭套接字。
socket.close();
}
catch(Throwable t) {
t.printStackTrace();
}
}
}

//测试程序
Udp_Chat.java
import java.io.*;
import java.net.*;
public class UDP_Chat {
public UDP_Chat(String s){
}
public static void main(String args[])throws Exception{
Message a = new Message("阿飞的卡","211.92.155.200" ,"211.92.155.200");
new Sender(a).start();
new Receiver().start();
}
}