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.ObjectattachmentAttribute to store connection attachmentprivate java.nio.channels.ByteChannelchannelthe possibly wrapped channel object whose selection is controlled bykeyprivate java.lang.Integerclosecodeprivate java.lang.Booleanclosedremotelyprivate java.lang.Stringclosemessagestatic intDEFAULT_PORTThe default port of WebSockets, as defined in the spec.static intDEFAULT_WSS_PORTThe default wss port of WebSockets, as defined in the spec.private DraftdraftThe draft which is used by this websocketprivate booleanflushandclosestateWhen true no further frames may be submitted to be sentprivate ClientHandshakehandshakerequeststores the handshake sent by this websocket ( Role.CLIENT only )java.util.concurrent.BlockingQueue<java.nio.ByteBuffer>inQueueQueue of buffers that need to be processedprivate java.nio.channels.SelectionKeykeyprivate java.util.List<Draft>knownDraftsA list of drafts available for this websocketprivate longlastPongAttribute, when the last pong was receivedprivate org.slf4j.LoggerlogLogger instancejava.util.concurrent.BlockingQueue<java.nio.ByteBuffer>outQueueQueue of buffers that need to be sent to the client.static intRCVBUFInitial buffer sizeprivate ReadyStatereadyStateThe current state of the connectionprivate java.lang.StringresourceDescriptorprivate RoleroleThe role which this websocket takes in the connectionprivate java.lang.ObjectsynchronizeWriteObjectAttribut to synchronize the writeprivate java.nio.ByteBuffertmpHandshakeBytesthe bytes of an incomplete received handshakeprivate WebSocketServer.WebSocketWorkerworkerThreadHelper variable meant to store the thread which ( exclusively ) triggers this objects decode method.private WebSocketListenerwslThe 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 voidclose()Convenience function which behaves like close(CloseFrame.NORMAL)voidclose(int code)sends the closing handshake.voidclose(int code, java.lang.String message)sends the closing handshake.voidclose(int code, java.lang.String message, boolean remote)voidclose(InvalidDataException e)voidcloseConnection()protected voidcloseConnection(int code, boolean remote)voidcloseConnection(int code, java.lang.String message)This will close the connection immediately without a proper close handshake.voidcloseConnection(int code, java.lang.String message, boolean remote)This will close the connection immediately without a proper close handshake.private voidcloseConnectionDueToInternalServerError(java.lang.RuntimeException exception)Close the connection if there was a server error by a RuntimeExceptionprivate voidcloseConnectionDueToWrongHandshake(InvalidDataException exception)Close the connection if the received handshake was not correctvoiddecode(java.nio.ByteBuffer socketBuffer)Method to decode the provided ByteBufferprivate voiddecodeFrames(java.nio.ByteBuffer socketBuffer)private booleandecodeHandshake(java.nio.ByteBuffer socketBufferNew)Returns whether the handshake phase has is completed.voideot()voidflushAndClose(int code, java.lang.String message, boolean remote)private java.nio.ByteBuffergenerateHttpResponseDueToError(int errorCode)Generate a simple response for the corresponding endpoint to indicate some error<T> TgetAttachment()Getter for the connection attachment.java.nio.channels.ByteChannelgetChannel()DraftgetDraft()Getter for the draft(package private) longgetLastPong()Getter for the last pong receivedjava.net.InetSocketAddressgetLocalSocketAddress()Returns the address of the endpoint this socket is bound to, ornullif it is not bound.IProtocolgetProtocol()Returns the used Sec-WebSocket-Protocol for this websocket connectionReadyStategetReadyState()Retrieve the WebSocket 'ReadyState'.java.net.InetSocketAddressgetRemoteSocketAddress()Returns the address of the endpoint this socket is connected to, ornullif it is unconnected.java.lang.StringgetResourceDescriptor()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.SelectionKeygetSelectionKey()javax.net.ssl.SSLSessiongetSSLSession()Returns the ssl session of websocket, if ssl/wss is used for this instance.WebSocketListenergetWebSocketListener()Getter for the websocket listenerWebSocketServer.WebSocketWorkergetWorkerThread()booleanhasBufferedData()Checks if the websocket has buffered databooleanhasSSLSupport()Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connectionbooleanisClosed()Is the websocket in the state CLOSEDbooleanisClosing()Is the websocket in the state CLOSINGbooleanisFlushAndClose()Returns true when no further frames may be submitted
This happens before the socket connection is closed.booleanisOpen()Is the websocket in the state OPENprivate voidopen(Handshakedata d)voidsend(byte[] bytes)Send Binary data (plain bytes) to the other end.voidsend(java.lang.String text)Send Text data to the other end.voidsend(java.nio.ByteBuffer bytes)Send Binary data (plain bytes) to the other end.private voidsend(java.util.Collection<Framedata> frames)voidsendFragmentedFrame(Opcode op, java.nio.ByteBuffer buffer, boolean fin)Allows to send continuous/fragmented frames conveniently.voidsendFrame(java.util.Collection<Framedata> frames)Send a collection of frames to the other endvoidsendFrame(Framedata framedata)Send a frame to the other endvoidsendPing()Send a ping to the other end<T> voidsetAttachment(T attachment)Setter for an attachment on the socket connection.voidsetChannel(java.nio.channels.ByteChannel channel)voidsetSelectionKey(java.nio.channels.SelectionKey key)voidsetWorkerThread(WebSocketServer.WebSocketWorker workerThread)voidstartHandshake(ClientHandshakeBuilder handshakedata)java.lang.StringtoString()voidupdateLastPong()Update the timestamp when the last pong was receivedprivate voidwrite(java.nio.ByteBuffer buf)private voidwrite(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 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 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:WebSocketsends 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 transferred over the wire also they will be forwarded to onClose/onWebsocketClose.- Parameters:
code- the closing codemessage- the closing messageremote- Indicates who "generated"code.
truemeans that this endpoint received thecodefrom the other endpoint.
false means this endpoint decided to send the given code,
remotemay also be true if this endpoint started the closing handshake since the other endpoint may not simply echo thecodebut 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:WebSocketThis 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:
closeConnectionin 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:WebSocketsends 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:
sendin 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:
sendin 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:WebSocketSend 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:WebSocketAllows 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:
sendFragmentedFramein 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:WebSocketSend a collection of frames to the other end
-
sendFrame
public void sendFrame(Framedata framedata)
Description copied from interface:WebSocketSend a frame to the other end
-
sendPing
public void sendPing() throws java.lang.NullPointerExceptionDescription copied from interface:WebSocketSend a ping to the other end
-
hasBufferedData
public boolean hasBufferedData()
Description copied from interface:WebSocketChecks if the websocket has buffered data- Specified by:
hasBufferedDatain 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:WebSocketIs the websocket in the state OPEN
-
isClosing
public boolean isClosing()
Description copied from interface:WebSocketIs the websocket in the state CLOSING
-
isFlushAndClose
public boolean isFlushAndClose()
Description copied from interface:WebSocketReturns true when no further frames may be submitted
This happens before the socket connection is closed.- Specified by:
isFlushAndClosein interfaceWebSocket- Returns:
- true when no further frames may be submitted
-
isClosed
public boolean isClosed()
Description copied from interface:WebSocketIs the websocket in the state CLOSED
-
getReadyState
public ReadyState getReadyState()
Description copied from interface:WebSocketRetrieve the WebSocket 'ReadyState'. This represents the state of the connection. It returns a numerical value, as per W3C WebSockets specs.- Specified by:
getReadyStatein 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:
toStringin classjava.lang.Object
-
getRemoteSocketAddress
public java.net.InetSocketAddress getRemoteSocketAddress()
Description copied from interface:WebSocketReturns the address of the endpoint this socket is connected to, ornullif it is unconnected.- Specified by:
getRemoteSocketAddressin interfaceWebSocket- Returns:
- the remote socket address or null, if this socket is unconnected
-
getLocalSocketAddress
public java.net.InetSocketAddress getLocalSocketAddress()
Description copied from interface:WebSocketReturns the address of the endpoint this socket is bound to, ornullif it is not bound.- Specified by:
getLocalSocketAddressin interfaceWebSocket- Returns:
- the local socket address or null, if this socket is not bound
-
close
public void close()
Description copied from interface:WebSocketConvenience function which behaves like close(CloseFrame.NORMAL)
-
getResourceDescriptor
public java.lang.String getResourceDescriptor()
Description copied from interface:WebSocketReturns 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:
getResourceDescriptorin interfaceWebSocket- 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:WebSocketGetter for the connection attachment.- Specified by:
getAttachmentin interfaceWebSocket- Type Parameters:
T- The type of the attachment- Returns:
- Returns the user attachment
-
hasSSLSupport
public boolean hasSSLSupport()
Description copied from interface:WebSocketDoes this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection- Specified by:
hasSSLSupportin 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:WebSocketReturns the ssl session of websocket, if ssl/wss is used for this instance.- Specified by:
getSSLSessionin interfaceWebSocket- Returns:
- the ssl session of this websocket instance
-
getProtocol
public IProtocol getProtocol()
Description copied from interface:WebSocketReturns the used Sec-WebSocket-Protocol for this websocket connection- Specified by:
getProtocolin interfaceWebSocket- Returns:
- the Sec-WebSocket-Protocol or null, if no draft available
-
setAttachment
public <T> void setAttachment(T attachment)
Description copied from interface:WebSocketSetter for an attachment on the socket connection. The attachment may be of any type.- Specified by:
setAttachmentin 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)
-
-