Package org.java_websocket
Class WebSocketImpl
java.lang.Object
org.java_websocket.WebSocketImpl
- All Implemented Interfaces:
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
FieldsModifier and TypeFieldDescriptionprivate Object
Attribute to store connection attachmentprivate ByteChannel
the possibly wrapped channel object whose selection is controlled bykey
private Integer
private Boolean
private String
static final int
The default port of WebSockets, as defined in the spec.static final int
The default wss port of WebSockets, as defined in the spec.private Draft
The draft which is used by this websocketprivate boolean
When true no further frames may be submitted to be sentprivate ClientHandshake
stores the handshake sent by this websocket ( Role.CLIENT only )final BlockingQueue
<ByteBuffer> Queue of buffers that need to be processedprivate SelectionKey
A list of drafts available for this websocketprivate long
Attribute, when the last pong was receivedprivate final org.slf4j.Logger
Logger instancefinal BlockingQueue
<ByteBuffer> Queue of buffers that need to be sent to the client.private ReadyState
The current state of the connectionprivate String
private Role
The role which this websocket takes in the connectionprivate final Object
Attribut to synchronize the writeprivate ByteBuffer
the bytes of an incomplete received handshakeprivate WebSocketServer.WebSocketWorker
Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method.private final WebSocketListener
The listener to notify of WebSocket events. -
Constructor Summary
ConstructorsConstructorDescriptionWebSocketImpl
(WebSocketListener listener, List<Draft> drafts) Creates a websocket with server roleWebSocketImpl
(WebSocketListener listener, Draft draft) creates a websocket with client role -
Method Summary
Modifier and TypeMethodDescriptionvoid
close()
Convenience function which behaves like close(CloseFrame.NORMAL)void
close
(int code) sends the closing handshake.void
sends the closing handshake.void
void
void
protected void
closeConnection
(int code, boolean remote) void
closeConnection
(int code, String message) This will close the connection immediately without a proper close handshake.void
closeConnection
(int code, String message, boolean remote) This will close the connection immediately without a proper close handshake.private void
Close the connection if there was a server error by a RuntimeExceptionprivate void
Close the connection if the received handshake was not correctvoid
decode
(ByteBuffer socketBuffer) Method to decode the provided ByteBufferprivate void
decodeFrames
(ByteBuffer socketBuffer) private boolean
decodeHandshake
(ByteBuffer socketBufferNew) Returns whether the handshake phase has is completed.void
eot()
void
flushAndClose
(int code, String message, boolean remote) private ByteBuffer
generateHttpResponseDueToError
(int errorCode) Generate a simple response for the corresponding endpoint to indicate some error<T> T
Getter for the connection attachment.getDraft()
Getter for the draft(package private) long
Getter for the last pong receivedReturns the address of the endpoint this socket is bound to, ornull
if it is not bound.Returns the used Sec-WebSocket-Protocol for this websocket connectionRetrieve the WebSocket 'ReadyState'.Returns the address of the endpoint this socket is connected to, ornull
if it is unconnected.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.Returns the ssl session of websocket, if ssl/wss is used for this instance.Getter for the websocket listenerboolean
Checks if the websocket has buffered databoolean
Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connectionboolean
isClosed()
Is the websocket in the state CLOSEDboolean
Is the websocket in the state CLOSINGboolean
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
void
send
(byte[] bytes) Send Binary data (plain bytes) to the other end.void
Send Text data to the other end.void
send
(ByteBuffer bytes) Send Binary data (plain bytes) to the other end.private void
send
(Collection<Framedata> frames) void
sendFragmentedFrame
(Opcode op, ByteBuffer buffer, boolean fin) Allows to send continuous/fragmented frames conveniently.void
sendFrame
(Collection<Framedata> frames) Send a collection of frames to the other endvoid
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
(ByteChannel channel) void
void
setWorkerThread
(WebSocketServer.WebSocketWorker workerThread) void
startHandshake
(ClientHandshakeBuilder handshakedata) toString()
void
Update the timestamp when the last pong was receivedprivate void
write
(ByteBuffer buf) private void
write
(List<ByteBuffer> bufs) Write a list of bytebuffer (frames in binary form) into the outgoing queue
-
Field Details
-
DEFAULT_PORT
public static final int DEFAULT_PORTThe 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:
-
DEFAULT_WSS_PORT
public static final int DEFAULT_WSS_PORTThe 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:
-
log
private final org.slf4j.Logger logLogger instance- Since:
- 1.4.0
-
outQueue
Queue of buffers that need to be sent to the client. -
inQueue
Queue of buffers that need to be processed -
wsl
The listener to notify of WebSocket events. -
key
-
channel
the possibly wrapped channel object whose selection is controlled bykey
-
workerThread
Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method. -
flushandclosestate
private boolean flushandclosestateWhen true no further frames may be submitted to be sent -
readyState
The current state of the connection -
knownDrafts
A list of drafts available for this websocket -
draft
The draft which is used by this websocket -
role
The role which this websocket takes in the connection -
tmpHandshakeBytes
the bytes of an incomplete received handshake -
handshakerequest
stores the handshake sent by this websocket ( Role.CLIENT only ) -
closemessage
-
closecode
-
closedremotely
-
resourceDescriptor
-
lastPong
private long lastPongAttribute, when the last pong was received -
synchronizeWriteObject
Attribut to synchronize the write -
attachment
Attribute to store connection attachment- Since:
- 1.3.7
-
-
Constructor Details
-
WebSocketImpl
Creates a websocket with server role- Parameters:
listener
- The listener for this instancedrafts
- The drafts which should be used
-
WebSocketImpl
creates a websocket with client role- Parameters:
listener
- The listener for this instancedraft
- The draft which should be used
-
-
Method Details
-
decode
Method to decode the provided ByteBuffer- Parameters:
socketBuffer
- the ByteBuffer to decode
-
decodeHandshake
Returns whether the handshake phase has is completed. In case of a broken handshake this will be never the case. -
decodeFrames
-
closeConnectionDueToWrongHandshake
Close the connection if the received handshake was not correct- Parameters:
exception
- the InvalidDataException causing this problem
-
closeConnectionDueToInternalServerError
Close the connection if there was a server error by a RuntimeException- Parameters:
exception
- the RuntimeException causing this problem
-
generateHttpResponseDueToError
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
-
close
Description copied from interface:WebSocket
sends the closing handshake. may be send in response to an other handshake. -
closeConnection
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
.
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
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 interfaceWebSocket
- Parameters:
code
- the closing codemessage
- the closing message
-
flushAndClose
-
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
-
send
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
Send Binary data (plain bytes) to the other end.- Specified by:
send
in interfaceWebSocket
- Parameters:
bytes
- the binary data to send- Throws:
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
-
sendFragmentedFrame
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
Description copied from interface:WebSocket
Send a collection of frames to the other end -
sendFrame
Description copied from interface:WebSocket
Send a frame to the other end -
sendPing
Description copied from interface:WebSocket
Send a ping to the other end- Specified by:
sendPing
in interfaceWebSocket
- Throws:
NullPointerException
-
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
- Throws:
InvalidHandshakeException
-
write
-
write
Write a list of bytebuffer (frames in binary form) into the outgoing queue- Parameters:
bufs
- the list of bytebuffer
-
open
-
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
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
- Parameters:
key
- the selection key of this implementation
-
getSelectionKey
- Returns:
- the selection key of this implementation
-
toString
-
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:
- the remote socket address or null, if this socket is unconnected
-
getLocalSocketAddress
Description copied from interface:WebSocket
Returns the address of the endpoint this socket is bound to, ornull
if it is not bound.- Specified by:
getLocalSocketAddress
in interfaceWebSocket
- Returns:
- the local socket address or null, if this socket is not bound
-
getDraft
Description copied from interface:WebSocket
Getter for the draft -
close
public void close()Description copied from interface:WebSocket
Convenience function which behaves like close(CloseFrame.NORMAL) -
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 received- Returns:
- the timestamp for the last received pong
-
updateLastPong
public void updateLastPong()Update the timestamp when the last pong was received -
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
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
-
getProtocol
Description copied from interface:WebSocket
Returns the used Sec-WebSocket-Protocol for this websocket connection- Specified by:
getProtocol
in interfaceWebSocket
- 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 interfaceWebSocket
- Type Parameters:
T
- The type of the attachment- Parameters:
attachment
- The object to be attached to the user
-
getChannel
-
setChannel
-
getWorkerThread
-
setWorkerThread
-