Package org.java_websocket
Class WebSocketImpl
- java.lang.Object
-
- org.java_websocket.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 attachmentprivate java.nio.channels.ByteChannel
channel
the possibly wrapped channel object whose selection is controlled bykey
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 websocketprivate boolean
flushandclosestate
When true no further frames may be submitted to be sentprivate 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 processedprivate java.nio.channels.SelectionKey
key
private java.util.List<Draft>
knownDrafts
A list of drafts available for this websocketprivate long
lastPong
Attribute, when the last pong was recievedprivate org.slf4j.Logger
log
Logger instancejava.util.concurrent.BlockingQueue<java.nio.ByteBuffer>
outQueue
Queue of buffers that need to be sent to the client.static int
RCVBUF
Initial buffer sizeprivate ReadyState
readyState
The current state of the connectionprivate java.lang.String
resourceDescriptor
private Role
role
The role which this websocket takes in the connectionprivate java.lang.Object
synchronizeWriteObject
Attribut to synchronize the writeprivate java.nio.ByteBuffer
tmpHandshakeBytes
the bytes of an incomplete received handshakeprivate 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.
-
Constructor Summary
Constructors Constructor Description WebSocketImpl(WebSocketListener listener, java.util.List<Draft> drafts)
Creates a websocket with server roleWebSocketImpl(WebSocketListener listener, Draft draft)
creates a websocket with client role
-
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 RuntimeExceptionprivate void
closeConnectionDueToWrongHandshake(InvalidDataException exception)
Close the connection if the received handshake was not correctvoid
decode(java.nio.ByteBuffer socketBuffer)
Method to decode the provided ByteBufferprivate 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 recievedjava.net.InetSocketAddress
getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to.ReadyState
getReadyState()
Retrieve the WebSocket 'ReadyState'.java.net.InetSocketAddress
getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, ornull
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 listenerWebSocketServer.WebSocketWorker
getWorkerThread()
boolean
hasBufferedData()
Checks if the websocket has buffered databoolean
hasSSLSupport()
Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connectionboolean
isClosed()
Is the websocket in the state CLOSEDboolean
isClosing()
Is the websocket in the state CLOSINGboolean
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 OPENprivate 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 endvoid
sendFrame(Framedata framedata)
Send a frame to the other endvoid
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 receivedprivate 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
-
-
-
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
-
RCVBUF
public static final int RCVBUF
Initial buffer size- 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 bykey
-
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 recieved
-
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 instancedrafts
- 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 instancedraft
- 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.
-
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 transfered over the wire also they will be forwarded to onClose/onWebsocketClose.- Parameters:
code
- the closing codemessage
- the closing messageremote
- Indicates who "generated"code
.
true
means that this endpoint received thecode
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 thecode
but close the connection the same time this endpoint does do but with an othercode
.
-
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 transfered over the wire also they will be forwarded to onClose/onWebsocketClose.- Specified by:
closeConnection
in interfaceWebSocket
- Parameters:
code
- the closing codemessage
- 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.
-
close
public void close(InvalidDataException e)
-
send
public void send(java.lang.String text)
Send Text data to the other end.- Specified by:
send
in interfaceWebSocket
- 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 interfaceWebSocket
- Parameters:
bytes
- the binary data to send- Throws:
java.lang.IllegalArgumentException
- the data is nullWebsocketNotConnectedException
- 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.
-
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 interfaceWebSocket
- 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
-
sendFrame
public void sendFrame(Framedata framedata)
Description copied from interface:WebSocket
Send a frame to the other end
-
sendPing
public void sendPing() throws java.lang.NullPointerException
Description copied from interface:WebSocket
Send a ping to the other end
-
hasBufferedData
public boolean hasBufferedData()
Description copied from interface:WebSocket
Checks if the websocket has buffered data- Specified by:
hasBufferedData
in interfaceWebSocket
- Returns:
- has the websocket buffered data
-
startHandshake
public void startHandshake(ClientHandshakeBuilder handshakedata) throws InvalidHandshakeException
- Throws:
InvalidHandshakeException
-
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
-
open
private void open(Handshakedata d)
-
isOpen
public boolean isOpen()
Description copied from interface:WebSocket
Is the websocket in the state OPEN
-
isClosing
public boolean isClosing()
Description copied from interface:WebSocket
Is the websocket in the state 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 interfaceWebSocket
- 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
-
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 interfaceWebSocket
- 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 classjava.lang.Object
-
getRemoteSocketAddress
public java.net.InetSocketAddress getRemoteSocketAddress()
Description copied from interface:WebSocket
Returns the address of the endpoint this socket is connected to, ornull
if it is unconnected.- Specified by:
getRemoteSocketAddress
in interfaceWebSocket
- Returns:
- never returns null
-
getLocalSocketAddress
public java.net.InetSocketAddress getLocalSocketAddress()
Description copied from interface:WebSocket
Returns the address of the endpoint this socket is bound to.- Specified by:
getLocalSocketAddress
in interfaceWebSocket
- Returns:
- never returns null
-
close
public void close()
Description copied from interface:WebSocket
Convenience function which behaves like close(CloseFrame.NORMAL)
-
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 interfaceWebSocket
- Returns:
- Returns the decoded path component of this URI.
-
getLastPong
long getLastPong()
Getter for the last pong recieved- Returns:
- the timestamp for the last recieved 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 interfaceWebSocket
- 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 interfaceWebSocket
- 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 interfaceWebSocket
- Returns:
- the ssl session of this websocket instance
-
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 interfaceWebSocket
- 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)
-
getWorkerThread
public WebSocketServer.WebSocketWorker getWorkerThread()
-
setWorkerThread
public void setWorkerThread(WebSocketServer.WebSocketWorker workerThread)
-
-