Why doesn't ServerSocket call NetworknOnMainThread while Socket does?

server = new ServerSocket(PORT);

      

does not throw NetworkOnMainThreadException in my application which I think should be doing and editing code to run on another thread until

socket= new Socket(ADDRESS,PORT);

      

indeed throws NetworkOnMainThreadException. Am I missing something or is this a bug that needs to be fixed?

+3


source to share


2 answers


Why? new ServerSocket(...)

is just a local operation. It is not associated with any real network activity whereas it new Socket(...)

does, and it can block for a minute or so.



+3


source


When you call new Socket (ADDRESS, PORT),

private Socket(SocketAddress address, SocketAddress localAddr,
413                    boolean stream) throws IOException {
414         setImpl();
415 
416         // backward compatibility
417         if (address == null)
418             throw new NullPointerException();
419 
420         try {
421             createImpl(stream);
422             if (localAddr != null)
423                 bind(localAddr);
424             if (address != null)
425                 connect(address);
426         } catch (IOException e) {
427             close();
428             throw e;
429         }
430     }

      

Creates a stream. whereasserver = new ServerSocket(PORT);



public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
230        setImpl();
231        if (port < 0 || port > 0xFFFF)
232            throw new IllegalArgumentException(
233                       "Port value out of range: " + port);
234        if (backlog < 1)
235          backlog = 50;
236        try {
237            bind(new InetSocketAddress(bindAddr, port), backlog);
238        } catch(SecurityException e) {
239            close();
240            throw e;
241        } catch(IOException e) {
242            close();
243            throw e;
244        }
245    }

      

NOTICE there is no connect();

, which does not cause any of these methods to be related to network operations, so you will not getNetworkOnMainThreadException

+1


source







All Articles