0

嗨,我想遍历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

4

3 回答 3

2

使用可能,ArrayList首先存储您的套接字:

ArrayList<DatagramSocket> socketList = new ArrayList<DatagramSocket>();
socketList.add(new DatagramSocket());
socketList.add(new DatagramSocket());
socketList.add(new DatagramSocket());
socketList.add(new DatagramSocket());

然后循环socketList

for(int i = 0; i < portList.size(); i++) {
    socketList.get(i).connect(InetAddress.getLocalHost(), portList.get(i));
}

这是假设您拥有相同数量的端口并DatagramSocketsocketList. 否则,它将NullPointer在循环中的某个地方抛出一个。

更新

来自user1753100的解决方案:

ArrayList<DatagramSocket> socketList = new ArrayList<DatagramSocket>();
for (int j = 0; j < portList.size(); j++) {
    socketList.add(new DatagramSocket());
}
于 2012-10-18T03:53:23.693 回答
1

拉塞尔的回答很好。总结一下,这就是我要写的:

//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);
}
于 2012-10-18T04:08:25.903 回答
0
ArrayList<DatagramSocket> socketList = new ArrayList<DatagramSocket>();

for(int i=0;i<portList.size();i++)

 {
   socketList.add(new DatagramSocket().connect(InetAddress.getLocalHost(), portList.get(i));
}
于 2012-10-18T04:07:44.270 回答