Class WebSocketImpl

  • All Implemented Interfaces:
    WebSocket

    public class WebSocketImpl
    extends java.lang.Object
    implements WebSocket
    Represents one end (client or server) of a single WebSocketImpl connection. Takes care of the "handshake" phase, then allows for easy sending of text frames, and receiving frames through an event-based model.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private java.lang.Object attachment
      Attribute to store connection attachment
      private java.nio.channels.ByteChannel channel
      the possibly wrapped channel object whose selection is controlled by key
      private java.lang.Integer closecode  
      private java.lang.Boolean closedremotely  
      private java.lang.String closemessage  
      static int DEFAULT_PORT
      The default port of WebSockets, as defined in the spec.
      static int DEFAULT_WSS_PORT
      The default wss port of WebSockets, as defined in the spec.
      private Draft draft
      The draft which is used by this websocket
      private boolean flushandclosestate
      When true no further frames may be submitted to be sent
      private ClientHandshake handshakerequest
      stores the handshake sent by this websocket ( Role.CLIENT only )
      java.util.concurrent.BlockingQueue<java.nio.ByteBuffer> inQueue
      Queue of buffers that need to be processed
      private java.nio.channels.SelectionKey key  
      private java.util.List<Draft> knownDrafts
      A list of drafts available for this websocket
      private long lastPong
      Attribute, when the last pong was received
      private org.slf4j.Logger log
      Logger instance
      java.util.concurrent.BlockingQueue<java.nio.ByteBuffer> outQueue
      Queue of buffers that need to be sent to the client.
      static int RCVBUF
      Initial buffer size
      private ReadyState readyState
      The current state of the connection
      private java.lang.String resourceDescriptor  
      private Role role
      The role which this websocket takes in the connection
      private java.lang.Object synchronizeWriteObject
      Attribut to synchronize the write
      private java.nio.ByteBuffer tmpHandshakeBytes
      the bytes of an incomplete received handshake
      private WebSocketServer.WebSocketWorker workerThread
      Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method.
      private WebSocketListener wsl
      The listener to notify of WebSocket events.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void close()
      Convenience function which behaves like close(CloseFrame.NORMAL)
      void close​(int code)
      sends the closing handshake.
      void close​(int code, java.lang.String message)
      sends the closing handshake.
      void close​(int code, java.lang.String message, boolean remote)  
      void close​(InvalidDataException e)  
      void closeConnection()  
      protected void closeConnection​(int code, boolean remote)  
      void closeConnection​(int code, java.lang.String message)
      This will close the connection immediately without a proper close handshake.
      void closeConnection​(int code, java.lang.String message, boolean remote)
      This will close the connection immediately without a proper close handshake.
      private void closeConnectionDueToInternalServerError​(java.lang.RuntimeException exception)
      Close the connection if there was a server error by a RuntimeException
      private void closeConnectionDueToWrongHandshake​(InvalidDataException exception)
      Close the connection if the received handshake was not correct
      void decode​(java.nio.ByteBuffer socketBuffer)
      Method to decode the provided ByteBuffer
      private void decodeFrames​(java.nio.ByteBuffer socketBuffer)  
      private boolean decodeHandshake​(java.nio.ByteBuffer socketBufferNew)
      Returns whether the handshake phase has is completed.
      void eot()  
      void flushAndClose​(int code, java.lang.String message, boolean remote)  
      private java.nio.ByteBuffer generateHttpResponseDueToError​(int errorCode)
      Generate a simple response for the corresponding endpoint to indicate some error
      <T> T getAttachment()
      Getter for the connection attachment.
      java.nio.channels.ByteChannel getChannel()  
      Draft getDraft()
      Getter for the draft
      (package private) long getLastPong()
      Getter for the last pong received
      java.net.InetSocketAddress getLocalSocketAddress()
      Returns the address of the endpoint this socket is bound to, or null if it is not bound.
      IProtocol getProtocol()
      Returns the used Sec-WebSocket-Protocol for this websocket connection
      ReadyState getReadyState()
      Retrieve the WebSocket 'ReadyState'.
      java.net.InetSocketAddress getRemoteSocketAddress()
      Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
      java.lang.String getResourceDescriptor()
      Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2
      If the opening handshake has not yet happened it will return null.
      java.nio.channels.SelectionKey getSelectionKey()  
      javax.net.ssl.SSLSession getSSLSession()
      Returns the ssl session of websocket, if ssl/wss is used for this instance.
      WebSocketListener getWebSocketListener()
      Getter for the websocket listener
      WebSocketServer.WebSocketWorker getWorkerThread()  
      boolean hasBufferedData()
      Checks if the websocket has buffered data
      boolean hasSSLSupport()
      Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection
      boolean isClosed()
      Is the websocket in the state CLOSED
      boolean isClosing()
      Is the websocket in the state CLOSING
      boolean isFlushAndClose()
      Returns true when no further frames may be submitted
      This happens before the socket connection is closed.
      boolean isOpen()
      Is the websocket in the state OPEN
      private void open​(Handshakedata d)  
      void send​(byte[] bytes)
      Send Binary data (plain bytes) to the other end.
      void send​(java.lang.String text)
      Send Text data to the other end.
      void send​(java.nio.ByteBuffer bytes)
      Send Binary data (plain bytes) to the other end.
      private void send​(java.util.Collection<Framedata> frames)  
      void sendFragmentedFrame​(Opcode op, java.nio.ByteBuffer buffer, boolean fin)
      Allows to send continuous/fragmented frames conveniently.
      void sendFrame​(java.util.Collection<Framedata> frames)
      Send a collection of frames to the other end
      void sendFrame​(Framedata framedata)
      Send a frame to the other end
      void sendPing()
      Send a ping to the other end
      <T> void setAttachment​(T attachment)
      Setter for an attachment on the socket connection.
      void setChannel​(java.nio.channels.ByteChannel channel)  
      void setSelectionKey​(java.nio.channels.SelectionKey key)  
      void setWorkerThread​(WebSocketServer.WebSocketWorker workerThread)  
      void startHandshake​(ClientHandshakeBuilder handshakedata)  
      java.lang.String toString()  
      void updateLastPong()
      Update the timestamp when the last pong was received
      private void write​(java.nio.ByteBuffer buf)  
      private void write​(java.util.List<java.nio.ByteBuffer> bufs)
      Write a list of bytebuffer (frames in binary form) into the outgoing queue
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • DEFAULT_PORT

        public static final int DEFAULT_PORT
        The default port of WebSockets, as defined in the spec. If the nullary constructor is used, DEFAULT_PORT will be the port the WebSocketServer is binded to. Note that ports under 1024 usually require root permissions.
        See Also:
        Constant Field Values
      • DEFAULT_WSS_PORT

        public static final int DEFAULT_WSS_PORT
        The default wss port of WebSockets, as defined in the spec. If the nullary constructor is used, DEFAULT_WSS_PORT will be the port the WebSocketServer is binded to. Note that ports under 1024 usually require root permissions.
        See Also:
        Constant Field Values
      • log

        private final org.slf4j.Logger log
        Logger instance
        Since:
        1.4.0
      • outQueue

        public final java.util.concurrent.BlockingQueue<java.nio.ByteBuffer> outQueue
        Queue of buffers that need to be sent to the client.
      • inQueue

        public final java.util.concurrent.BlockingQueue<java.nio.ByteBuffer> inQueue
        Queue of buffers that need to be processed
      • wsl

        private final WebSocketListener wsl
        The listener to notify of WebSocket events.
      • key

        private java.nio.channels.SelectionKey key
      • channel

        private java.nio.channels.ByteChannel channel
        the possibly wrapped channel object whose selection is controlled by key
      • workerThread

        private WebSocketServer.WebSocketWorker workerThread
        Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method.
      • flushandclosestate

        private boolean flushandclosestate
        When true no further frames may be submitted to be sent
      • readyState

        private volatile ReadyState readyState
        The current state of the connection
      • knownDrafts

        private java.util.List<Draft> knownDrafts
        A list of drafts available for this websocket
      • draft

        private Draft draft
        The draft which is used by this websocket
      • role

        private Role role
        The role which this websocket takes in the connection
      • tmpHandshakeBytes

        private java.nio.ByteBuffer tmpHandshakeBytes
        the bytes of an incomplete received handshake
      • handshakerequest

        private ClientHandshake handshakerequest
        stores the handshake sent by this websocket ( Role.CLIENT only )
      • closemessage

        private java.lang.String closemessage
      • closecode

        private java.lang.Integer closecode
      • closedremotely

        private java.lang.Boolean closedremotely
      • resourceDescriptor

        private java.lang.String resourceDescriptor
      • lastPong

        private long lastPong
        Attribute, when the last pong was received
      • synchronizeWriteObject

        private final java.lang.Object synchronizeWriteObject
        Attribut to synchronize the write
      • attachment

        private java.lang.Object attachment
        Attribute to store connection attachment
        Since:
        1.3.7
    • Constructor Detail

      • WebSocketImpl

        public WebSocketImpl​(WebSocketListener listener,
                             java.util.List<Draft> drafts)
        Creates a websocket with server role
        Parameters:
        listener - The listener for this instance
        drafts - The drafts which should be used
      • WebSocketImpl

        public WebSocketImpl​(WebSocketListener listener,
                             Draft draft)
        creates a websocket with client role
        Parameters:
        listener - The listener for this instance
        draft - The draft which should be used
    • Method Detail

      • decode

        public void decode​(java.nio.ByteBuffer socketBuffer)
        Method to decode the provided ByteBuffer
        Parameters:
        socketBuffer - the ByteBuffer to decode
      • decodeHandshake

        private boolean decodeHandshake​(java.nio.ByteBuffer socketBufferNew)
        Returns whether the handshake phase has is completed. In case of a broken handshake this will be never the case.
      • decodeFrames

        private void decodeFrames​(java.nio.ByteBuffer socketBuffer)
      • closeConnectionDueToWrongHandshake

        private void closeConnectionDueToWrongHandshake​(InvalidDataException exception)
        Close the connection if the received handshake was not correct
        Parameters:
        exception - the InvalidDataException causing this problem
      • closeConnectionDueToInternalServerError

        private void closeConnectionDueToInternalServerError​(java.lang.RuntimeException exception)
        Close the connection if there was a server error by a RuntimeException
        Parameters:
        exception - the RuntimeException causing this problem
      • generateHttpResponseDueToError

        private java.nio.ByteBuffer generateHttpResponseDueToError​(int errorCode)
        Generate a simple response for the corresponding endpoint to indicate some error
        Parameters:
        errorCode - the http error code
        Returns:
        the complete response as ByteBuffer
      • close

        public void close​(int code,
                          java.lang.String message,
                          boolean remote)
      • close

        public void close​(int code,
                          java.lang.String message)
        Description copied from interface: WebSocket
        sends the closing handshake. may be send in response to an other handshake.
        Specified by:
        close in interface WebSocket
        Parameters:
        code - the closing code
        message - the closing message
      • closeConnection

        public void closeConnection​(int code,
                                    java.lang.String message,
                                    boolean remote)
        This will close the connection immediately without a proper close handshake. The code and the message therefore won't be transferred over the wire also they will be forwarded to onClose/onWebsocketClose.
        Parameters:
        code - the closing code
        message - the closing message
        remote - Indicates who "generated" code.
        true means that this endpoint received the code from the other endpoint.
        false means this endpoint decided to send the given code,
        remote may also be true if this endpoint started the closing handshake since the other endpoint may not simply echo the code but close the connection the same time this endpoint does do but with an other code.
      • closeConnection

        protected void closeConnection​(int code,
                                       boolean remote)
      • closeConnection

        public void closeConnection()
      • closeConnection

        public void closeConnection​(int code,
                                    java.lang.String message)
        Description copied from interface: WebSocket
        This will close the connection immediately without a proper close handshake. The code and the message therefore won't be transferred over the wire also they will be forwarded to onClose/onWebsocketClose.
        Specified by:
        closeConnection in interface WebSocket
        Parameters:
        code - the closing code
        message - the closing message
      • flushAndClose

        public void flushAndClose​(int code,
                                  java.lang.String message,
                                  boolean remote)
      • eot

        public void eot()
      • close

        public void close​(int code)
        Description copied from interface: WebSocket
        sends the closing handshake. may be send in response to an other handshake.
        Specified by:
        close in interface WebSocket
        Parameters:
        code - the closing code
      • send

        public void send​(java.lang.String text)
        Send Text data to the other end.
        Specified by:
        send in interface WebSocket
        Parameters:
        text - the text data to send
        Throws:
        WebsocketNotConnectedException - websocket is not yet connected
      • send

        public void send​(java.nio.ByteBuffer bytes)
        Send Binary data (plain bytes) to the other end.
        Specified by:
        send in interface WebSocket
        Parameters:
        bytes - the binary data to send
        Throws:
        java.lang.IllegalArgumentException - the data is null
        WebsocketNotConnectedException - websocket is not yet connected
      • send

        public void send​(byte[] bytes)
        Description copied from interface: WebSocket
        Send Binary data (plain bytes) to the other end.
        Specified by:
        send in interface WebSocket
        Parameters:
        bytes - the byte array to send
      • send

        private void send​(java.util.Collection<Framedata> frames)
      • sendFragmentedFrame

        public void sendFragmentedFrame​(Opcode op,
                                        java.nio.ByteBuffer buffer,
                                        boolean fin)
        Description copied from interface: WebSocket
        Allows to send continuous/fragmented frames conveniently.
        For more into on this frame type see http://tools.ietf.org/html/rfc6455#section-5.4

        If the first frame you send is also the last then it is not a fragmented frame and will received via onMessage instead of onFragmented even though it was send by this method.

        Specified by:
        sendFragmentedFrame in interface WebSocket
        Parameters:
        op - This is only important for the first frame in the sequence. Opcode.TEXT, Opcode.BINARY are allowed.
        buffer - The buffer which contains the payload. It may have no bytes remaining.
        fin - true means the current frame is the last in the sequence.
      • sendFrame

        public void sendFrame​(java.util.Collection<Framedata> frames)
        Description copied from interface: WebSocket
        Send a collection of frames to the other end
        Specified by:
        sendFrame in interface WebSocket
        Parameters:
        frames - the frames to send to the other end
      • sendFrame

        public void sendFrame​(Framedata framedata)
        Description copied from interface: WebSocket
        Send a frame to the other end
        Specified by:
        sendFrame in interface WebSocket
        Parameters:
        framedata - the frame to send to the other end
      • sendPing

        public void sendPing()
                      throws java.lang.NullPointerException
        Description copied from interface: WebSocket
        Send a ping to the other end
        Specified by:
        sendPing in interface WebSocket
        Throws:
        java.lang.NullPointerException
      • hasBufferedData

        public boolean hasBufferedData()
        Description copied from interface: WebSocket
        Checks if the websocket has buffered data
        Specified by:
        hasBufferedData in interface WebSocket
        Returns:
        has the websocket buffered data
      • write

        private void write​(java.nio.ByteBuffer buf)
      • write

        private void write​(java.util.List<java.nio.ByteBuffer> bufs)
        Write a list of bytebuffer (frames in binary form) into the outgoing queue
        Parameters:
        bufs - the list of bytebuffer
      • isOpen

        public boolean isOpen()
        Description copied from interface: WebSocket
        Is the websocket in the state OPEN
        Specified by:
        isOpen in interface WebSocket
        Returns:
        state equals ReadyState.OPEN
      • isClosing

        public boolean isClosing()
        Description copied from interface: WebSocket
        Is the websocket in the state CLOSING
        Specified by:
        isClosing in interface WebSocket
        Returns:
        state equals ReadyState.CLOSING
      • isFlushAndClose

        public boolean isFlushAndClose()
        Description copied from interface: WebSocket
        Returns true when no further frames may be submitted
        This happens before the socket connection is closed.
        Specified by:
        isFlushAndClose in interface WebSocket
        Returns:
        true when no further frames may be submitted
      • isClosed

        public boolean isClosed()
        Description copied from interface: WebSocket
        Is the websocket in the state CLOSED
        Specified by:
        isClosed in interface WebSocket
        Returns:
        state equals ReadyState.CLOSED
      • getReadyState

        public ReadyState getReadyState()
        Description copied from interface: WebSocket
        Retrieve the WebSocket 'ReadyState'. This represents the state of the connection. It returns a numerical value, as per W3C WebSockets specs.
        Specified by:
        getReadyState in interface WebSocket
        Returns:
        Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED'
      • setSelectionKey

        public void setSelectionKey​(java.nio.channels.SelectionKey key)
        Parameters:
        key - the selection key of this implementation
      • getSelectionKey

        public java.nio.channels.SelectionKey getSelectionKey()
        Returns:
        the selection key of this implementation
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • getRemoteSocketAddress

        public java.net.InetSocketAddress getRemoteSocketAddress()
        Description copied from interface: WebSocket
        Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
        Specified by:
        getRemoteSocketAddress in interface WebSocket
        Returns:
        the remote socket address or null, if this socket is unconnected
      • getLocalSocketAddress

        public java.net.InetSocketAddress getLocalSocketAddress()
        Description copied from interface: WebSocket
        Returns the address of the endpoint this socket is bound to, or null if it is not bound.
        Specified by:
        getLocalSocketAddress in interface WebSocket
        Returns:
        the local socket address or null, if this socket is not bound
      • getDraft

        public Draft getDraft()
        Description copied from interface: WebSocket
        Getter for the draft
        Specified by:
        getDraft in interface WebSocket
        Returns:
        the used draft
      • close

        public void close()
        Description copied from interface: WebSocket
        Convenience function which behaves like close(CloseFrame.NORMAL)
        Specified by:
        close in interface WebSocket
      • getResourceDescriptor

        public java.lang.String getResourceDescriptor()
        Description copied from interface: WebSocket
        Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2
        If the opening handshake has not yet happened it will return null.
        Specified by:
        getResourceDescriptor in interface WebSocket
        Returns:
        Returns the decoded path component of this URI.
      • getLastPong

        long getLastPong()
        Getter for the last pong received
        Returns:
        the timestamp for the last received pong
      • updateLastPong

        public void updateLastPong()
        Update the timestamp when the last pong was received
      • getWebSocketListener

        public WebSocketListener getWebSocketListener()
        Getter for the websocket listener
        Returns:
        the websocket listener associated with this instance
      • getAttachment

        public <T> T getAttachment()
        Description copied from interface: WebSocket
        Getter for the connection attachment.
        Specified by:
        getAttachment in interface WebSocket
        Type Parameters:
        T - The type of the attachment
        Returns:
        Returns the user attachment
      • hasSSLSupport

        public boolean hasSSLSupport()
        Description copied from interface: WebSocket
        Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection
        Specified by:
        hasSSLSupport in interface WebSocket
        Returns:
        true, if the websocket does use wss and therefore has a SSLSession
      • getSSLSession

        public javax.net.ssl.SSLSession getSSLSession()
        Description copied from interface: WebSocket
        Returns the ssl session of websocket, if ssl/wss is used for this instance.
        Specified by:
        getSSLSession in interface WebSocket
        Returns:
        the ssl session of this websocket instance
      • getProtocol

        public IProtocol getProtocol()
        Description copied from interface: WebSocket
        Returns the used Sec-WebSocket-Protocol for this websocket connection
        Specified by:
        getProtocol in interface WebSocket
        Returns:
        the Sec-WebSocket-Protocol or null, if no draft available
      • setAttachment

        public <T> void setAttachment​(T attachment)
        Description copied from interface: WebSocket
        Setter for an attachment on the socket connection. The attachment may be of any type.
        Specified by:
        setAttachment in interface WebSocket
        Type Parameters:
        T - The type of the attachment
        Parameters:
        attachment - The object to be attached to the user
      • getChannel

        public java.nio.channels.ByteChannel getChannel()
      • setChannel

        public void setChannel​(java.nio.channels.ByteChannel channel)