看了下UDP编程的书写了个简单的例子代码如下
Java代码
import javaioIOException;
import DatagramPacket;
import DatagramSocket;
import InetAddress;
import SocketException;
public class UDPReceive {
public static void main(String[] args) {
Integer port = ;
byte[] buffer = new byte[];
try {
DatagramSocket datagramSocket = new DatagramSocket(port);
DatagramPacket datagramPacket = new DatagramPacket(buffer
bufferlength);
try {
for (;;) {
Systemoutprintln(begin receive data);
datagramSocketreceive(datagramPacket);
Systemoutprintln(datagramPacketgetAddress()getAddress()toString()+=======+new String(datagramPacketgetData()));
datagramPacketsetLength(datagramPacketgetData()toString()length());
}
} catch (IOException e) {
eprintStackTrace();
}
} catch (SocketException e) {
eprintStackTrace();
}
}
}
这个类用来接受消息
Java代码
import javaioIOException;
import DatagramPacket;
import DatagramSocket;
import InetAddress;
import SocketException;
import UnknownHostException;
public class UDPSend {
public static void main(String[] args) {
try {
for (;;) {
DatagramSocket sendSocket = new DatagramSocket();
DatagramPacket dataPack = new DatagramPacket(
hello welcome to study javagetBytes()
hello welcome to study javalength() InetAddress
getByName() new Integer());
try {
sendSocketsend(dataPack);
sendSocketclose();
} catch (IOException e) {
eprintStackTrace();
}
}
} catch (SocketException e) {
eprintStackTrace();
} catch (UnknownHostException e) {
eprintStackTrace();
}
}
}
这个类用来发送消息