嗨,我想遍历我拥有的n个端口列表,并为每个端口创建一个DatagramSocket:

for(int i = 0; i < portList.size(); i++) {
    DatagramSocket socket[i] = new DatagramSocket();
    socket[i].connect(InetAddress.getLocalHost(), portList.get(i));
}


我知道我不应该使用socket[i]。只是表达我的意思,以上内容会生成:

DatagramSocket socket1 = new DatagramSocket();
socket1.connect(InetAddress.getLocalHost(), 2000);

DatagramSocket socket2 = new DatagramSocket();
socket2.connect(InetAddress.getLocalHost(), 2001);

DatagramSocket socket3 = new DatagramSocket();
socket3.connect(InetAddress.getLocalHost(), 2002);

DatagramSocket socket4 = new DatagramSocket();
socket4.connect(InetAddress.getLocalHost(), 2003);


我不太擅长Java,所以这可能是一个愚蠢的问题:P

最佳答案

罗素的答案很好。总结一下,这是我要写的:

//get local host
InetAddress localHost = InetAddress.getLocalHost();

//make a List to hold the sockets
//we know how many there will be so use that capacity
List<DatagramSocket> datagramSockets =
        new ArrayList<DatagramSocket>(portList.size());

//for each port,
for (Integer port : portList) {
    //instantiate a new socket
    DatagramSocket datagramSocket = new DatagramSocket();
    //add it to the list
    datagramSockets.add(datagramSocket);
    //connect it using the port
    datagramSocket.connect(localHost, port);
}

10-01 00:29