1.使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello,world”
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class fashong {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket ds = new DatagramSocket(3000);
String str = "hollo world";
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),7788);
ds.send(dp);
ds.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class jieshou {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
byte[] buf = new byte[1024];
DatagramSocket ds = new DatagramSocket(7788);
//DatagramPacket(byte[] buf, int length) :用于接收端,length是缓存区buf的长度
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp); //该方法用于将数据填充到DatagramPacket中
dp.getData();//返回接受到的数据
String str = new String (dp.getData());
System.out.println(str);
ds.close();
}
}