udp接收和发送数据
接收数据
package it.com.cc.fourtween;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket(10086);
byte []bys=new byte[1024];
DatagramPacket dp=new DatagramPacket(bys,bys.length);
ds.receive(dp);
System.out.println("数据是:"+new String(dp.getData(),0,dp.getLength()));
ds.close();
}
}
发送数据
package it.com.cc.fourtween;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class SendDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
byte[]bys=“hello,udp”.getBytes();
// int length = bys.length;
// InetAddress address = InetAddress.getByName(“192.168.31.106”);
// int port=10086;
// DatagramPacket dp=new DatagramPacket(bys,length,address,port);
DatagramPacket dp=new DatagramPacket(bys,bys.length,InetAddress.getByName(“192.168.31.106”),10086);
ds.send(dp);
ds.close();
}
}