服务器端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket ds=new DatagramSocket(9999);
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
byte[] data = dp.getData();
int length = dp.getLength();
InetAddress ipClient = dp.getAddress();
int port = dp.getPort();
String str=new String(data,0,length);
System.out.println("服务器端收到:"+str);
String dataOut="HELLO CLIENT,"+str;
DatagramPacket dpOut=new DatagramPacket(
dataOut.getBytes(),
dataOut.length(),
ipClient,
port);
ds.send(dpOut);
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket ds=new DatagramSocket();
String data="Hello UDPSEver!";
DatagramPacket dp=
new DatagramPacket(
data.getBytes(),
data.length(),
InetAddress.getLocalHost(),
9999);
ds.send(dp);
byte[] buf=new byte[1024];
DatagramPacket dpIn=new DatagramPacket(buf, buf.length);
ds.receive(dpIn);
System.out.println(new String(dpIn.getData(),0,dpIn.getLength()));
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}