java udp 接收数据
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPReceive {
public static void main(String[] args){
Integer port = 2345;
byte[] buffer = new byte[2048];
try {
DatagramSocket datagramSocket = new DatagramSocket(port);
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
try {
for (int i=0;i<3;i++) {
System.out.println("begin receive data....");
datagramSocket.receive(datagramPacket);
System.out.println(datagramPacket.getAddress().getAddress().toString()+"======="+new String(datagramPacket.getData()));
datagramPacket.setLength(datagramPacket.getData().toString().length());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
java udp 发送数据
package udp;
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 UDPSend {
public static void main(String[] args) {
String str = "abcdefghigklmn......";
try {
for (int i =0 ;i<1;i++) {
DatagramSocket sendSocket = new DatagramSocket();
DatagramPacket dataPack = new DatagramPacket(
str.getBytes(),str.length(), InetAddress.getByName("127.0.0.1"), new Integer(2345));
try {
sendSocket.send(dataPack);
sendSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}