Package org.java_websocket.client
Class WebSocketClient
- java.lang.Object
-
- org.java_websocket.WebSocketAdapter
-
- org.java_websocket.AbstractWebSocket
-
- org.java_websocket.client.WebSocketClient
-
- All Implemented Interfaces:
Runnable
,WebSocket
,WebSocketListener
public abstract class WebSocketClient extends AbstractWebSocket implements Runnable, WebSocket
A subclass must implement at least onOpen, onClose, and onMessage to be useful. At runtime the user is expected to establish a connection viaconnect()
, then receive events likeonMessage(String)
via the overloaded methods and tosend(String)
data to the server.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from interface org.java_websocket.WebSocket
WebSocket.READYSTATE, WebSocket.Role
-
-
Field Summary
Fields Modifier and Type Field Description protected URI
uri
The URI this channel is supposed to connect to.-
Fields inherited from interface org.java_websocket.WebSocket
DEFAULT_PORT, DEFAULT_WSS_PORT
-
-
Constructor Summary
Constructors Constructor Description WebSocketClient(URI serverUri)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI.WebSocketClient(URI serverUri, Map<String,String> httpHeaders)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI.WebSocketClient(URI serverUri, Draft protocolDraft)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI.WebSocketClient(URI serverUri, Draft protocolDraft, Map<String,String> httpHeaders)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI.WebSocketClient(URI serverUri, Draft protocolDraft, Map<String,String> httpHeaders, int connectTimeout)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
close()
Initiates the websocket close handshake.void
close(int code)
sends the closing handshake.void
close(int code, String message)
sends the closing handshake.void
closeBlocking()
Same asclose
but blocks until the websocket closed or failed to do so.void
closeConnection(int code, String message)
This will close the connection immediately without a proper close handshake.void
connect()
Initiates the websocket connection.boolean
connectBlocking()
Same asconnect
but blocks until the websocket connected or failed to do so.boolean
connectBlocking(long timeout, TimeUnit timeUnit)
Same asconnect
but blocks with a timeout until the websocket connected or failed to do so.<T> T
getAttachment()
Getter for the connection attachment.WebSocket
getConnection()
Getter for the engineprotected Collection<WebSocket>
getConnections()
Getter to get all the currently available connectionsDraft
getDraft()
Returns the protocol version this channel uses.
For more infos see https://github.com/TooTallNate/Java-WebSocket/wiki/DraftsInetSocketAddress
getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to.InetSocketAddress
getLocalSocketAddress(WebSocket conn)
WebSocket.READYSTATE
getReadyState()
This represents the state of the connection.InetSocketAddress
getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, ornull
if it is unconnected.InetSocketAddress
getRemoteSocketAddress(WebSocket conn)
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.Socket
getSocket()
Returns the socket to allow Hostname VerificationURI
getURI()
Returns the URI that this WebSocketClient is connected to.boolean
hasBufferedData()
Checks if the websocket has buffered databoolean
isClosed()
Is the websocket in the state CLOSEDboolean
isClosing()
Is the websocket in the state CLOSINGboolean
isConnecting()
Deprecated.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 OPENabstract void
onClose(int code, String reason, boolean remote)
Called after the websocket connection has been closed.void
onCloseInitiated(int code, String reason)
Send when this peer sends a close handshakevoid
onClosing(int code, String reason, boolean remote)
Called as soon as no further frames are acceptedabstract void
onError(Exception ex)
Called when errors occurs.void
onFragment(Framedata frame)
Deprecated.abstract void
onMessage(String message)
Callback for string messages received from the remote hostvoid
onMessage(ByteBuffer bytes)
Callback for binary messages received from the remote hostabstract void
onOpen(ServerHandshake handshakedata)
Called after an opening handshake has been performed and the given websocket is ready to be written on.void
onWebsocketClose(WebSocket conn, int code, String reason, boolean remote)
Calls subclass' implementation of onClose.void
onWebsocketCloseInitiated(WebSocket conn, int code, String reason)
send when this peer sends a close handshakevoid
onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote)
Called as soon as no further frames are acceptedvoid
onWebsocketError(WebSocket conn, Exception ex)
Calls subclass' implementation of onIOError.void
onWebsocketMessage(WebSocket conn, String message)
Calls subclass' implementation of onMessage.void
onWebsocketMessage(WebSocket conn, ByteBuffer blob)
Called when an entire binary frame has been received.void
onWebsocketMessageFragment(WebSocket conn, Framedata frame)
This default implementation does not do anything.void
onWebsocketOpen(WebSocket conn, Handshakedata handshake)
Calls subclass' implementation of onOpen.void
onWriteDemand(WebSocket conn)
This method is used to inform the selector thread that there is data queued to be written to the socket.void
reconnect()
Reinitiates the websocket connection.boolean
reconnectBlocking()
Same asreconnect
but blocks until the websocket reconnected or failed to do so.void
run()
void
send(byte[] data)
Sends binary data to the connected webSocket server.void
send(String text)
Sends text to the connected websocket server.void
send(ByteBuffer bytes)
Send Binary data (plain bytes) to the other end.void
sendFragmentedFrame(Framedata.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
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
setProxy(Proxy proxy)
Method to set a proxy for this connectionvoid
setSocket(Socket socket)
Accepts bound and unbound sockets.
This method must be called beforeconnect
.-
Methods inherited from class org.java_websocket.AbstractWebSocket
getConnectionLostTimeout, isReuseAddr, isTcpNoDelay, setConnectionLostTimeout, setReuseAddr, setTcpNoDelay, startConnectionLostTimer, stopConnectionLostTimer
-
Methods inherited from class org.java_websocket.WebSocketAdapter
onWebsocketHandshakeReceivedAsClient, onWebsocketHandshakeReceivedAsServer, onWebsocketHandshakeSentAsClient, onWebsocketPing, onWebsocketPong
-
-
-
-
Field Detail
-
uri
protected URI uri
The URI this channel is supposed to connect to.
-
-
Constructor Detail
-
WebSocketClient
public WebSocketClient(URI serverUri)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. The connection will be established once you call connect.- Parameters:
serverUri
- the server URI to connect to
-
WebSocketClient
public WebSocketClient(URI serverUri, Draft protocolDraft)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. The connection will be established once you call connect.- Parameters:
serverUri
- the server URI to connect toprotocolDraft
- The draft which should be used for this connection
-
WebSocketClient
public WebSocketClient(URI serverUri, Map<String,String> httpHeaders)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. The connection will be established once you call connect.- Parameters:
serverUri
- the server URI to connect tohttpHeaders
- Additional HTTP-Headers- Since:
- 1.3.8
-
WebSocketClient
public WebSocketClient(URI serverUri, Draft protocolDraft, Map<String,String> httpHeaders)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. The connection will be established once you call connect.- Parameters:
serverUri
- the server URI to connect toprotocolDraft
- The draft which should be used for this connectionhttpHeaders
- Additional HTTP-Headers- Since:
- 1.3.8
-
WebSocketClient
public WebSocketClient(URI serverUri, Draft protocolDraft, Map<String,String> httpHeaders, int connectTimeout)
Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. The connection will be established once you call connect.- Parameters:
serverUri
- the server URI to connect toprotocolDraft
- The draft which should be used for this connectionhttpHeaders
- Additional HTTP-HeadersconnectTimeout
- The Timeout for the connection
-
-
Method Detail
-
getURI
public URI getURI()
Returns the URI that this WebSocketClient is connected to.- Returns:
- the URI connected to
-
getDraft
public Draft getDraft()
Returns the protocol version this channel uses.
For more infos see https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts
-
getSocket
public Socket getSocket()
Returns the socket to allow Hostname Verification- Returns:
- the socket used for this connection
-
reconnect
public void reconnect()
Reinitiates the websocket connection. This method does not block.- Since:
- 1.3.8
-
reconnectBlocking
public boolean reconnectBlocking() throws InterruptedException
Same asreconnect
but blocks until the websocket reconnected or failed to do so.- Returns:
- Returns whether it succeeded or not.
- Throws:
InterruptedException
- Thrown when the threads get interrupted- Since:
- 1.3.8
-
connect
public void connect()
Initiates the websocket connection. This method does not block.
-
connectBlocking
public boolean connectBlocking() throws InterruptedException
Same asconnect
but blocks until the websocket connected or failed to do so.- Returns:
- Returns whether it succeeded or not.
- Throws:
InterruptedException
- Thrown when the threads get interrupted
-
connectBlocking
public boolean connectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException
Same asconnect
but blocks with a timeout until the websocket connected or failed to do so.- Parameters:
timeout
- The connect timeouttimeUnit
- The timeout time unit- Returns:
- Returns whether it succeeded or not.
- Throws:
InterruptedException
- Thrown when the threads get interrupted
-
close
public void close()
Initiates the websocket close handshake. This method does not block
In oder to make sure the connection is closed usecloseBlocking
-
closeBlocking
public void closeBlocking() throws InterruptedException
Same asclose
but blocks until the websocket closed or failed to do so.- Throws:
InterruptedException
- Thrown when the threads get interrupted
-
send
public void send(String text) throws NotYetConnectedException
Sends text to the connected websocket server.- Specified by:
send
in interfaceWebSocket
- Parameters:
text
- The string which will be transmitted.- Throws:
NotYetConnectedException
- websocket is not yet connected
-
send
public void send(byte[] data) throws NotYetConnectedException
Sends binary data to the connected webSocket server.- Specified by:
send
in interfaceWebSocket
- Parameters:
data
- The byte-Array of data to send to the WebSocket server.- Throws:
NotYetConnectedException
- websocket is not yet connected
-
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
-
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
-
getConnections
protected Collection<WebSocket> getConnections()
Description copied from class:AbstractWebSocket
Getter to get all the currently available connections- Specified by:
getConnections
in classAbstractWebSocket
- Returns:
- the currently available connections
-
sendPing
public void sendPing() throws NotYetConnectedException
Description copied from interface:WebSocket
Send a ping to the other end- Specified by:
sendPing
in interfaceWebSocket
- Throws:
NotYetConnectedException
- websocket is not yet connected
-
getReadyState
public WebSocket.READYSTATE getReadyState()
This represents the state of the connection.- Specified by:
getReadyState
in interfaceWebSocket
- Returns:
- Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED'
-
onWebsocketMessage
public final void onWebsocketMessage(WebSocket conn, String message)
Calls subclass' implementation of onMessage.- Specified by:
onWebsocketMessage
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occurring on.message
- The UTF-8 decoded message that was received.
-
onWebsocketMessage
public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob)
Description copied from interface:WebSocketListener
Called when an entire binary frame has been received. Do whatever you want here...- Specified by:
onWebsocketMessage
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occurring on.blob
- The binary message that was received.
-
onWebsocketMessageFragment
public void onWebsocketMessageFragment(WebSocket conn, Framedata frame)
Description copied from class:WebSocketAdapter
This default implementation does not do anything. Go ahead and overwrite it- Specified by:
onWebsocketMessageFragment
in interfaceWebSocketListener
- Overrides:
onWebsocketMessageFragment
in classWebSocketAdapter
- Parameters:
conn
- The WebSocket instance this event is occurring on.frame
- The fragmented frame- See Also:
WebSocketListener.onWebsocketMessageFragment(WebSocket, Framedata)
-
onWebsocketOpen
public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake)
Calls subclass' implementation of onOpen.- Specified by:
onWebsocketOpen
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.handshake
- The handshake of the websocket instance
-
onWebsocketClose
public final void onWebsocketClose(WebSocket conn, int code, String reason, boolean remote)
Calls subclass' implementation of onClose.- Specified by:
onWebsocketClose
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.code
- The codes can be looked up here:CloseFrame
reason
- Additional information stringremote
- Returns whether or not the closing of the connection was initiated by the remote host.
-
onWebsocketError
public final void onWebsocketError(WebSocket conn, Exception ex)
Calls subclass' implementation of onIOError.- Specified by:
onWebsocketError
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.ex
- The exception that occurred.
Might be null if the exception is not related to any specific connection. For example if the server port could not be bound.
-
onWriteDemand
public final void onWriteDemand(WebSocket conn)
Description copied from interface:WebSocketListener
This method is used to inform the selector thread that there is data queued to be written to the socket.- Specified by:
onWriteDemand
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.
-
onWebsocketCloseInitiated
public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason)
Description copied from interface:WebSocketListener
send when this peer sends a close handshake- Specified by:
onWebsocketCloseInitiated
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.code
- The codes can be looked up here:CloseFrame
reason
- Additional information string
-
onWebsocketClosing
public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote)
Description copied from interface:WebSocketListener
Called as soon as no further frames are accepted- Specified by:
onWebsocketClosing
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.code
- The codes can be looked up here:CloseFrame
reason
- Additional information stringremote
- Returns whether or not the closing of the connection was initiated by the remote host.
-
onCloseInitiated
public void onCloseInitiated(int code, String reason)
Send when this peer sends a close handshake- Parameters:
code
- The codes can be looked up here:CloseFrame
reason
- Additional information string
-
onClosing
public void onClosing(int code, String reason, boolean remote)
Called as soon as no further frames are accepted- Parameters:
code
- The codes can be looked up here:CloseFrame
reason
- Additional information stringremote
- Returns whether or not the closing of the connection was initiated by the remote host.
-
getConnection
public WebSocket getConnection()
Getter for the engine- Returns:
- the engine
-
getLocalSocketAddress
public InetSocketAddress getLocalSocketAddress(WebSocket conn)
- Specified by:
getLocalSocketAddress
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.- Returns:
- Returns the address of the endpoint this socket is bound to.
- See Also:
WebSocket.getLocalSocketAddress()
-
getRemoteSocketAddress
public InetSocketAddress getRemoteSocketAddress(WebSocket conn)
- Specified by:
getRemoteSocketAddress
in interfaceWebSocketListener
- Parameters:
conn
- The WebSocket instance this event is occuring on.- Returns:
- Returns the address of the endpoint this socket is connected to, or
null
if it is unconnected. - See Also:
WebSocket.getRemoteSocketAddress()
-
onOpen
public abstract void onOpen(ServerHandshake handshakedata)
Called after an opening handshake has been performed and the given websocket is ready to be written on.- Parameters:
handshakedata
- The handshake of the websocket instance
-
onMessage
public abstract void onMessage(String message)
Callback for string messages received from the remote host- Parameters:
message
- The UTF-8 decoded message that was received.- See Also:
onMessage(ByteBuffer)
-
onClose
public abstract void onClose(int code, String reason, boolean remote)
Called after the websocket connection has been closed.- Parameters:
code
- The codes can be looked up here:CloseFrame
reason
- Additional information stringremote
- Returns whether or not the closing of the connection was initiated by the remote host.
-
onError
public abstract void onError(Exception ex)
Called when errors occurs. If an error causes the websocket connection to failonClose(int, String, boolean)
will be called additionally.
This method will be called primarily because of IO or protocol errors.
If the given exception is an RuntimeException that probably means that you encountered a bug.- Parameters:
ex
- The exception causing this error
-
onMessage
public void onMessage(ByteBuffer bytes)
Callback for binary messages received from the remote host- Parameters:
bytes
- The binary message that was received.- See Also:
onMessage(String)
-
onFragment
@Deprecated public void onFragment(Framedata frame)
Deprecated.Callback for fragmented frames- Parameters:
frame
- The fragmented frame- See Also:
WebSocket.sendFragmentedFrame(org.java_websocket.framing.Framedata.Opcode, ByteBuffer, boolean)
-
setProxy
public void setProxy(Proxy proxy)
Method to set a proxy for this connection- Parameters:
proxy
- the proxy to use for this websocket client
-
setSocket
public void setSocket(Socket socket)
Accepts bound and unbound sockets.
This method must be called beforeconnect
. If the given socket is not yet bound it will be bound to the uri specified in the constructor.- Parameters:
socket
- The socket which should be used for the connection
-
sendFragmentedFrame
public void sendFragmentedFrame(Framedata.Opcode op, 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.
-
isOpen
public boolean isOpen()
Description copied from interface:WebSocket
Is the websocket in the state OPEN
-
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
-
isClosing
public boolean isClosing()
Description copied from interface:WebSocket
Is the websocket in the state CLOSING
-
isConnecting
@Deprecated public boolean isConnecting()
Deprecated.Description copied from interface:WebSocket
Is the websocket in the state CONNECTING- Specified by:
isConnecting
in interfaceWebSocket
- Returns:
- state equals READYSTATE.CONNECTING
-
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
-
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(int code, 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, 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
-
send
public void send(ByteBuffer bytes) throws IllegalArgumentException, NotYetConnectedException
Description copied from interface:WebSocket
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 nullNotYetConnectedException
- websocket is not yet connected
-
sendFrame
public void sendFrame(Framedata framedata)
Description copied from interface:WebSocket
Send a frame to the other end
-
sendFrame
public void sendFrame(Collection<Framedata> frames)
Description copied from interface:WebSocket
Send a collection of frames to the other end
-
getLocalSocketAddress
public 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
-
getRemoteSocketAddress
public 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
-
getResourceDescriptor
public 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.
-
-