端口号1111 。为啥接收到的时候不是1111
我写的端口号1111 。为啥接收到的时候不是1111 呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; //可以使用双份该程序测试udp套接字 public class UDP0 { public static void main(String[] args) throws IOException { byte [] arr = new byte [ 128 ]; DatagramPacket p = new DatagramPacket(arr, 128 ); if (args[ 0 ].charAt( 0 ) == 'r' ){ //read DatagramSocket sock = new DatagramSocket( 1111 ); sock.receive(p); String word = new String(p.getData()); System.out.println( "From: " +p.getAddress()+ " :Port" +p.getPort()); //取出数据包中的地址和端口,执行结果端口号不一致 System.out.println(word); sock.close(); } else { //write DatagramSocket sock = new DatagramSocket(); p.setAddress(InetAddress.getByName(args[ 1 ])); //地址端口封装在数据包中 p.setPort( 1111 ); /// 我指定1111 sock.send(p); sock.close(); } } } |
不知道是不是端口号的问题啊。 我局域网发数据收不到。 跟远程主机发送。远程主机可以收到
分析:
先看API吧,每个函数的用途和功能,先了解清楚再说吧。
DatagramPacket.getPort() 返回的是远程主机的端口,不是本地端口。
套接字一般由4个部分组成,本地IP、本地端口、远程IIP、远程端口。
另外,发送代码中,没有看到设置数据的语句。