클라용 소켓 인터페이스부
서버용 소켓 인터페이스부

소켓 imple <-- 이것도 추상클래스로 빼놔서..

실제 추상화된 단계는
1.abstract class More ...AbstractPlainSocketImpl extends SocketImpl
2.class More ...PlainSocketImpl extends AbstractPlainSocketImpl
3.class More ...SocksSocketImpl extends PlainSocketImpl implements SocksConsts

하여튼.. 자신의 단계에서 가능한 메서드를 정의해두고 나머진 하위 클래스에게 맡겨버림..


1에서 볼만한건.. 클래스 멤버(static) 초기화 부분에서 먼짓을 하고 있는지!

79     static {
80         java.security.AccessController.doPrivileged(
81                   new sun.security.action.LoadLibraryAction("net"));
82     }

또한 create메서드에서 동기화 처리및 , 스트림 여부에 따라 udp 소켓 생성.. 리소스 매니저 사용..등

88     protected synchronized void More ...create(boolean stream) throws IOException {
89         fd = new FileDescriptor();
90         this.stream = stream;
91         if (!stream) {
92             ResourceManager.beforeUdpCreate();
93             try {
94                 socketCreate(false);
95             } catch (IOException ioe) {
96                 ResourceManager.afterUdpClose();
97                 fd = null;
98                 throw ioe;
99             }
100        } else {
101            socketCreate(true);
102        }
103        if (socket != null)
104            socket.setCreated();
105        if (serverSocket != null)
106            serverSocket.setCreated();
107    }

3에서 볼만한건..((SocketInputStream)in).read(data, received, len - received, remainingMillis(deadlineMillis));

117     private int More ...readSocksReply(InputStream in, byte[] data, long deadlineMillis) throws IOException {
118         int len = data.length;
119         int received = 0;
120         for (int attempts = 0; received < len && attempts < 3; attempts++) {
121             int count;
122             try {
123                 count = ((SocketInputStream)in).read(data, received, len - received, remainingMillis(deadlineMillis));
124             } catch (SocketTimeoutException e) {
125                 throw new SocketTimeoutException("Connect timed out");
126             }
127             if (count < 0)
128                 throw new SocketException("Malformed reply from SOCKS server");
129             received += count;
130         }
131         return received;
132     }

여튼 맞는지 모르겟지만,, 브릿지 패턴같음 


51 public
52 class More ...ServerSocket implements java.io.Closeable {
    

55 
56     private boolean created = false;
57     private boolean bound = false;
58     private boolean closed = false;
59     private Object closeLock = new Object();

    
63 
64     private SocketImpl impl;

   
68 
69     private boolean oldImpl = false;

    
75     More ...ServerSocket(SocketImpl impl) {
76         this.impl = impl;
77         impl.setServerSocket(this);
78     }

    

85 
86     public More ...ServerSocket() throws IOException {
87         setImpl();
88     }

    
//팩토리 클래스에서 실제 소켓 구현 클래스 얻고.. 추상 팩토리 패턴;;;
//시큐리티 매니저도.. 아.. 모르겠다..
SocketImpl
SocketImplFactory.createSocketImpl()
setSocketFactory(java.net.SocketImplFactory)
java.lang.SecurityManager.checkListen(int)
126
127    public More ...ServerSocket(int port) throws IOException {
128        this(port, 50, null);
129    }

    

180    public More ...ServerSocket(int port, int backlog) throws IOException {
181        this(port, backlog, null);
182    }


228
229    public More ...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    }

    

//아래의 AccessController.doPrivileged .. 내가 awt 분석하면서 많이본 코드 조각.. 
//특별한 권한을 부여한다는 건데..  아래보면 reflect를 통해 소켓구현 클래스에..
//정의된 connect메서드를 얻는다.  하여간.. 이코드의 존재 의미를 명확히 모르겠다..

254
255    SocketImpl More ...getImpl() throws SocketException {
256        if (!created)
257            createImpl();
258        return impl;
259    }
260
261    private void More ...checkOldImpl() {
262        if (impl == null)
263            return;
264        // SocketImpl.connect() is a protected method, therefore we need to use
265        // getDeclaredMethod, therefore we need permission to access the member
266        try {
267            AccessController.doPrivileged(
268                new PrivilegedExceptionAction<Void>() {
269                    public Void More ...run() throws NoSuchMethodException {
270                        Class[] cl = new Class[2];
271                        cl[0] = SocketAddress.class;
272                        cl[1] = Integer.TYPE;
273                        impl.getClass().getDeclaredMethod("connect", cl);
274                        return null;
275                    }
276                });
277        } catch (java.security.PrivilegedActionException e) {
278            oldImpl = true;
279        }
280    }
281
282    private void More ...setImpl() {
283        if (factory != null) {
284            impl = factory.createSocketImpl();
285            checkOldImpl();
286        } else {
287            // No need to do a checkOldImpl() here, we know it's an up to date
288            // SocketImpl!
289            impl = new SocksSocketImpl();
290        }
291        if (impl != null)
292            impl.setServerSocket(this);
293    }

 
300
301    void More ...createImpl() throws SocketException {
302        if (impl == null)
303            setImpl();
304        try {
305            impl.create(true);
306            created = true;
307        } catch (IOException e) {
308            throw new SocketException(e.getMessage());
309        }
310    }

328
329    public void More ...bind(SocketAddress endpoint) throws IOException {
330        bind(endpoint, 50);
331    }

    
//유효한 연결인지 체크하고, 시큐리티 검사하고, 바인드 하고 , 바로 리슨을 해주는 걸 확인..

357
358    public void More ...bind(SocketAddress endpoint, int backlog) throws IOException {
359        if (isClosed())
360            throw new SocketException("Socket is closed");
361        if (!oldImpl && isBound())
362            throw new SocketException("Already bound");
363        if (endpoint == null)
364            endpoint = new InetSocketAddress(0);
365        if (!(endpoint instanceof InetSocketAddress))
366            throw new IllegalArgumentException("Unsupported address type");
367        InetSocketAddress epoint = (InetSocketAddress) endpoint;
368        if (epoint.isUnresolved())
369            throw new SocketException("Unresolved address");
370        if (backlog < 1)
371          backlog = 50;
372        try {
373            SecurityManager security = System.getSecurityManager();
374            if (security != null)
375                security.checkListen(epoint.getPort());
376            getImpl().bind(epoint.getAddress(), epoint.getPort());
377            getImpl().listen(backlog);
378            bound = true;
379        } catch(SecurityException e) {
380            bound = false;
381            throw e;
382        } catch(IOException e) {
383            bound = false;
384            throw e;
385        }
386    }

    
398    public InetAddress More ...getInetAddress() {
399        if (!isBound())
400            return null;
401        try {
402            return getImpl().getInetAddress();
403        } catch (SocketException e) {
404            // nothing
405            // If we're bound, the impl has been created
406            // so we shouldn't get here
407        }
408        return null;
409    }

    
421    public int More ...getLocalPort() {
422        if (!isBound())
423            return -1;
424        try {
425            return getImpl().getLocalPort();
426        } catch (SocketException e) {
427            // nothing
428            // If we're bound, the impl has been created
429            // so we shouldn't get here
430        }
431        return -1;
432    }

    
449
450    public SocketAddress More ...getLocalSocketAddress() {
451        if (!isBound())
452            return null;
453        return new InetSocketAddress(getInetAddress(), getLocalPort());
454    }

 
484    public Socket More ...accept() throws IOException {
485        if (isClosed())
486            throw new SocketException("Socket is closed");
487        if (!isBound())
488            throw new SocketException("Socket is not bound yet");
489        Socket s = new Socket((SocketImpl) null);
490        implAccept(s);
491        return s;
492    }

//시큐리티 매니저의 역할에 대해 생각해볼것! (즉 외부인 네트워크를 통한 스트림 연결에대해 인증및, 권한 설정등의 보안 작업)
509
510    protected final void More ...implAccept(Socket s) throws IOException {
511        SocketImpl si = null;
512        try {
513            if (s.impl == null)
514              s.setImpl();
515            else {
516                s.impl.reset();
517            }
518            si = s.impl;
519            s.impl = null;
520            si.address = new InetAddress();
521            si.fd = new FileDescriptor();
522            getImpl().accept(si);
523
524            SecurityManager security = System.getSecurityManager();
525            if (security != null) {
526                security.checkAccept(si.getInetAddress().getHostAddress(),
527                                     si.getPort());
528            }
529        } catch (IOException e) {
530            if (si != null)
531                si.reset();
532            s.impl = si;
533            throw e;
534        } catch (SecurityException e) {
535            if (si != null)
536                si.reset();
537            s.impl = si;
538            throw e;
539        }
540        s.impl = si;
541        s.postAccept();
542    }

556
557    public void More ...close() throws IOException {
558        synchronized(closeLock) {
559            if (isClosed())
560                return;
561            if (created)
562                impl.close();
563            closed = true;
564        }
565    }


582
583    public ServerSocketChannel More ...getChannel() {
584        return null;
585    }

592
593    public boolean More ...isBound() {
594        // Before 1.3 ServerSockets were always bound during creation
595        return bound || oldImpl;
596    }

    

603
604    public boolean More ...isClosed() {
605        synchronized(closeLock) {
606            return closed;
607        }
608    }


625
626    public synchronized void More ...setSoTimeout(int timeout) throws SocketException {
627        if (isClosed())
628            throw new SocketException("Socket is closed");
629        getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
630    }

    
639
640    public synchronized int More ...getSoTimeout() throws IOException {
641        if (isClosed())
642            throw new SocketException("Socket is closed");
643        Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
644        /* extra type safety */
645        if (o instanceof Integer) {
646            return ((Integer) o).intValue();
647        } else {
648            return 0;
649        }
650    }


687
688    public void More ...setReuseAddress(boolean on) throws SocketException {
689        if (isClosed())
690            throw new SocketException("Socket is closed");
691        getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
692    }

    
702
703    public boolean More ...getReuseAddress() throws SocketException {
704        if (isClosed())
705            throw new SocketException("Socket is closed");
706        return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
707    }


714
715    public String More ...toString() {
716        if (!isBound())
717            return "ServerSocket[unbound]";
718        return "ServerSocket[addr=" + impl.getInetAddress() +
719                ",port=" + impl.getPort() +
720                ",localport=" + impl.getLocalPort()  + "]";
721    }
722
723    void More ...setBound() {
724        bound = true;
725    }
726
727    void More ...setCreated() {
728        created = true;
729    }

    
The factory for all server sockets.
733
734    private static SocketImplFactory factory = null;


760
761    public static synchronized void More ...setSocketFactory(SocketImplFactory fac) throws IOException {
762        if (factory != null) {
763            throw new SocketException("factory already defined");
764        }
765        SecurityManager security = System.getSecurityManager();
766        if (security != null) {
767            security.checkSetFactory();
768        }
769        factory = fac;
770    }


806
807     public synchronized void More ...setReceiveBufferSize (int size) throws SocketException {
808        if (!(size > 0)) {
809            throw new IllegalArgumentException("negative receive size");
810        }
811        if (isClosed())
812            throw new SocketException("Socket is closed");
813        getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
814    }

828
829    public synchronized int More ...getReceiveBufferSize()
830    throws SocketException{
831        if (isClosed())
832            throw new SocketException("Socket is closed");
833        int result = 0;
834        Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
835        if (o instanceof Integer) {
836            result = ((Integer)o).intValue();
837        }
838        return result;
839    }


878
879    public void More ...setPerformancePreferences(int connectionTime,
880                                          int latency,
881                                          int bandwidth)
882    {
883        /* Not implemented yet */
884    }
885
886}


'자바se api > net' 카테고리의 다른 글

네트워크 관련  (0) 2014.01.01
java.net.socket 파고들기2  (0) 2014.01.01
java.net 중 서버 소켓 -> IOCP -> NIO -> NODE JS + 팩토리 패턴  (0) 2014.01.01
by givingsheart 2014. 1. 1. 16:16