如何获得套接字列表 Java

How to have a list of sockets Java

基本上,我想要一个 'listen' 线程来创建一个主线程可以访问的套接字向量。我的听法是这样的

ServerSocket listener = new ServerSocket(port);
while (connections.size() < 9) {
    connections.add(listener.accept());
    System.out.println("Connected Person");
}

但我认为因为 java 通过引用传递,它只是将引用推送到向量上,所以当第二个连接进入时,现在 connections[0] 和 connetions[1] 是相同的插座,对吗?

此外,当该线程结束时,侦听器变量也随之结束,因此向量中充满了空套接字引用。我希望能够将套接字复制到向量中,但是每个指南都说我必须将复制功能添加到对象中,但我不知道如何使用预定义的 ServerSocket 类型。

编辑:这是一个 P2P 系统,其中每个用户都知道彼此的用户。此外,我的 'send' 函数循环遍历向量,将每个套接字发送到向量中。然后读取从向量中的每个套接字读取。 错误是套接字不是 receiving/sending

But I think because java works on passing by reference it's only pushing a reference on the vector, so when a second connection comes in, now connections[0] and connections[1] are the same sockets, right?

  1. Java 不是 pass-by-reference1。是pass-by-value。参见 Is Java "pass-by-reference" or "pass-by-value"?

    在这种情况下,传递的值(实际上是 returned)是对 Socket 对象的引用。

  2. 每次 accept() 方法 returns,它都会 return 引用不同的 Socket 对象。因此,connections.get(0)connections.get(1) 将引用不同的 Socket 对象。

Furthermore, when this thread dies, the listener variable dies, so then the vector is full of empty socket references.

没有。 Vector 可以充满“空”(即 nullSocket 引用的唯一方法是明确地将它们放在那里。您的代码不会执行此操作。您的代码将 non-null 引用放入 connections。即使相应的 Socket 对象关闭,它们也会留在那里。 (如果你想摆脱它们,你需要从 Vector.

I want to be able to copy the socket into the vector ...

Vector 不是这样的。 Vector 保存对象的引用,而不是对象。

此外,无法复制 Socket 对象。它们不可复制。

我认为你需要回到基础并理解 Java 中对象和引用之间的区别。因为从 Java 的角度来看,你所说的并没有多大意义。

Edit: this is for a P2P system where each user knows of each other user. Additionally, my 'send' function loops through the vetor, sending to each socket into the vector. Then reading reads from every socket in vector. The error is the sockets are not receiving/sending.

这可能是由很多原因造成的,我认为如果不看到 minimal reproducible example,我们就无法帮助您。


1 - 如果您看到一些文章声称 Java 是 pass-by-reference,请忽略它。要么作者不明白Java,要么不明白“pass-by-reference”的真正含义。 (或者他们争辩说“pass-by-reference” 应该 的意思与实际意思不同……这是一个非常糟糕的主意。它是“另类真理”的废话.. .就像一些微软人争论说 C 是一种 OO 语言一样!)