public static void send() throws Exception{ DatagramSocket s = new DatagramSocket(null); s.setReuseAddress(true); s.bind(new InetSocketAddress(8888)); byte[] b = new byte[100]; for(int i=0; i<b.length; i++){ b[i] = (byte)i; } DatagramPacket p = new DatagramPacket(b, 0, b.length, new InetSocketAddress("localhost", 9999)); s.send(p); }
public static void recv() throws Exception{ DatagramSocket s = new DatagramSocket(null); s.setReuseAddress(true); s.bind(new InetSocketAddress(9999)); byte[] b = new byte[100]; DatagramPacket p = new DatagramPacket(b, 0, b.length); s.receive(p); System.out.println(p.getAddress() + ":" + p.getPort() + " " + p.getLength()); }
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
构造数据报包,用来将长度为 length 偏移量为 offset 的包发送到指定主机上的指定端口号。我现在是发送的时候不光要指定接收的udp端口,而且还要从本机指定的端口发出
(示例:
DatagramSocket s = new DatagramSocket(null);
s.bind(new InetSocketAddress(8888));
这等价于:
DatagramSocket s = new DatagramSocket(8888);
两个例子都能创建能够在 UDP 8888 端口上接收广播的 DatagramSocket
)
可以的,
写个程序测试一下即可。
import java.net.*;class Test{
public static void main(String[] args) throws Exception{
if( args.length > 0 ){
System.out.println("to send");
send();
}else{
System.out.println("to recv");
recv();
}
}
public static void send() throws Exception{
DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress(8888));
byte[] b = new byte[100];
for(int i=0; i<b.length; i++){
b[i] = (byte)i;
}
DatagramPacket p = new DatagramPacket(b, 0, b.length, new InetSocketAddress("localhost", 9999));
s.send(p);
}
public static void recv() throws Exception{
DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress(9999));
byte[] b = new byte[100];
DatagramPacket p = new DatagramPacket(b, 0, b.length);
s.receive(p);
System.out.println(p.getAddress() + ":" + p.getPort() + " " + p.getLength());
}
};
DatagramSocket(int port)中port对于UDP,既是接收时监听的PORT,又是send(包)时用的发送的PORT。这是同一个啊。