创建一个生成新DatagramSockets的循环?

时间:2012-10-18 03:48:30

标签: java variables loops

您好我想遍历我拥有的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

3 个答案:

答案 0 :(得分: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));
}

这假设您拥有相同数量的端口,并在DatagramSocket中添加了socketList。否则,它将在循环中的某处抛出NullPointer

<强>更新

来自 user1753100 的解决方案:

ArrayList<DatagramSocket> socketList = new ArrayList<DatagramSocket>();
for (int j = 0; j < portList.size(); j++) {
    socketList.add(new DatagramSocket());
}

答案 1 :(得分: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);
}

答案 2 :(得分: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));
}