套接字数组Java

我正在创建服务器和客户端Java应用程序。 我想创建一个数组来存储我的套接字。我正在使用eclipse,当我输入这行时:

Socket[] sockets = new Socket[3]; 

Eclipse给出了一个错误,说“资源类型Socket []没有实现java.lang.AutoCloseable”。

我怎样才能解决这个问题?

谢谢

尝试/捕获声明:

 try ( Socket[] sockets = new Socket[3]; //Line giving me error ServerSocket serverSocket = new ServerSocket(Integer.parseInt(ip)); Socket clientSocket = serverSocket.accept(); ServerClient client = new ServerClient(clientSocket); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); //User input BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)) ) { String inputLine; while ((inputLine = in.readLine()) != null) { out.println(inputLine); } } catch (IOException e) { System.out.println("Exception caught when trying to listen on port " + port + " or listening for a connection"); System.out.println(e.getMessage()); continue; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } 

虽然Socket类本身实现了AutoCloseable接口,但套接字数组 却没有

换句话说:您无法打开或关闭数组。

try-with-resources块中定义的资源必须全部可自动关闭。 这就是它的用途。 Socket []不是AutoCloseable,因此无法在那里定义。 在尝试之前移动声明。 对于您收到错误的任何其他资源,同上。 不要将其视为一般声明块。 事实并非如此。

当我运行您的代码时,我收到此错误消息

 Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: try-with-resources not applicable to variable type (java.net.Socket[] cannot be converted to java.lang.AutoCloseable) 

我建议您在想要定义套接字数组时不要将try catch块与资源一起使用。

  try ( your rest of code ) { define your array here ---> Socket[] sockets = new Socket[3]; String inputLine; while ((inputLine = in.readLine()) != null) { out.println(inputLine); } } catch (IOException e) { your rest of code 

注意:Socket类实现了Closeable和AutoCloseable,但是在try块中无法像你想象的那样定义数组

您可以轻松地解决这个问题,只需创建一个包含套接字连接的类,然后构建此类对象的数组。

建立课程:

Class example { Socket con;

这里的构造函数和额外代码……

}

然后只需构建数组:

例子[] arr =新例子[3];