Array of Sockets Java

前端 未结 4 721
心在旅途
心在旅途 2021-01-15 13:37

I\'m creating server and client java applications. I would like to create an array to store my sockets in. I\'m using eclipse, and when I type in this line:

         


        
相关标签:
4条回答
  • 2021-01-15 14:01

    You can outsmart this problem easily, just create a class containing a socket connection, then build an array of this class object.

    Build the class:

    Class example { Socket con;

    The constructor and extra code here ...

    }

    Then just build the array:

    example[] arr=new example[3];

    0 讨论(0)
  • 2021-01-15 14:06

    When I run your code I recevie this error message

    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)
    

    I advice you not to use try catch block with resources when you want to define your socket array.

           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 
    

    Note: Socket class implements Closeable and AutoCloseable , yet array cannot be defined in try block like you tried to do

    0 讨论(0)
  • 2021-01-15 14:18

    The resources defined in a try-with-resources block must all be auto-closeable. That's what it's for. Socket[] is not AutoCloseable, so it cannot be defined there. Move the declaration before the try. Ditto for any other resources you get the error on. Don't treat it as a general declaration block. It isn't.

    0 讨论(0)
  • 2021-01-15 14:23

    While Socket class itself implements AutoCloseable interface, array of Sockets - does not.

    To put it in simple terms: you cannot open or close an array.

    0 讨论(0)
提交回复
热议问题