Package org.java_websocket.server
Class WebSocketServer
java.lang.Object
org.java_websocket.WebSocketAdapter
org.java_websocket.AbstractWebSocket
org.java_websocket.server.WebSocketServer
- All Implemented Interfaces:
Runnable
,WebSocketListener
WebSocketServer
is an abstract class that only takes care of the
HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the
server.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionclass
This class is used to process incoming data -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final InetSocketAddress
The port number that this WebSocket server should listen on.private static final int
private BlockingQueue
<ByteBuffer> private final Collection
<WebSocket> Holds the list of active WebSocket connections.protected List
<WebSocketServer.WebSocketWorker> The Draft of the WebSocket protocol the Server is adhering to.private List
<WebSocketImpl> private final AtomicBoolean
private final org.slf4j.Logger
Logger instanceprivate int
Attribute which allows you to configure the socket "backlog" parameter which determines how many client connections can be queued.private int
private final AtomicInteger
private Selector
The 'Selector' used to get event keys from the underlying socket.private Thread
private ServerSocketChannel
The socket channel for this WebSocket server.private WebSocketServerFactory
Fields inherited from class org.java_websocket.AbstractWebSocket
DEFAULT_READ_BUFFER_SIZE
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a WebSocketServer that will attempt to listen on port WebSocketImpl.DEFAULT_PORT.WebSocketServer
(InetSocketAddress address) Creates a WebSocketServer that will attempt to bind/listen on the given address.WebSocketServer
(InetSocketAddress address, int decodercount) WebSocketServer
(InetSocketAddress address, int decodercount, List<Draft> drafts) WebSocketServer
(InetSocketAddress address, int decodercount, List<Draft> drafts, Collection<WebSocket> connectionscontainer) Creates a WebSocketServer that will attempt to bind/listen on the given address, and comply withDraft
version draft.WebSocketServer
(InetSocketAddress address, List<Draft> drafts) WebSocketServer
(ServerSocketChannel existingChannel) -
Method Summary
Modifier and TypeMethodDescriptionprotected boolean
protected void
void
broadcast
(byte[] data) Send a byte array to all connected endpointsvoid
broadcast
(byte[] data, Collection<WebSocket> clients) Send a byte array to a specific collection of websocket connectionsvoid
Send a text to all connected endpointsvoid
broadcast
(String text, Collection<WebSocket> clients) Send a text to a specific collection of websocket connectionsvoid
broadcast
(ByteBuffer data) Send a ByteBuffer to all connected endpointsvoid
broadcast
(ByteBuffer data, Collection<WebSocket> clients) Send a ByteBuffer to a specific collection of websocket connectionsprivate static InetSocketAddress
checkAddressOfExistingChannel
(ServerSocketChannel existingChannel) private void
doAccept
(SelectionKey key, Iterator<SelectionKey> i) Execute a accept operationprivate void
Do an additional readprivate void
doBroadcast
(Object data, Collection<WebSocket> clients) Private method to cache all the frames to improve memory footprint and conversion timeprivate boolean
The websocket server can only be started onceprivate boolean
doRead
(SelectionKey key, Iterator<SelectionKey> i) Execute a read operationprivate void
Clean up everything after a shutdownprivate boolean
Setup the selector thread as well as basic server settingsprivate void
doWrite
(SelectionKey key) Execute a write operationprivate void
fillFrames
(Draft draft, Map<Draft, List<Framedata>> draftFrames, String strData, ByteBuffer byteData) Fills the draftFrames with new data for the broadcastReturns all currently connected clients.getDraft()
Get the list of active draftsint
Returns the currently configured maximum number of pending connections.int
getPort()
Gets the port number that this server listens on.private Socket
Getter to return the socket used by this specific connectionfinal WebSocketFactory
private void
handleFatal
(WebSocket conn, Exception e) private void
handleIOException
(SelectionKey key, WebSocket conn, IOException ex) abstract void
Called after the websocket connection has been closed.void
onCloseInitiated
(WebSocket conn, int code, String reason) void
protected boolean
onConnect
(SelectionKey key) Returns whether a new connection shall be accepted or not.
Therefore method is well suited to implement some kind of connection limitation.abstract void
Called when errors occurs.abstract void
Callback for string messages received from the remote hostvoid
onMessage
(WebSocket conn, ByteBuffer message) Callback for binary messages received from the remote hostabstract void
onOpen
(WebSocket conn, ClientHandshake handshake) Called after an opening handshake has been performed and the given websocket is ready to be written on.abstract void
onStart()
Called when the server started up successfully.final void
onWebsocketClose
(WebSocket conn, int code, String reason, boolean remote) Called afterWebSocket#close
is explicity called, or when the other end of the WebSocket connection is closed.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 acceptedfinal void
onWebsocketError
(WebSocket conn, Exception ex) Called if an exception worth noting occurred.final void
onWebsocketMessage
(WebSocket conn, String message) Called when an entire text frame has been received.final void
onWebsocketMessage
(WebSocket conn, ByteBuffer blob) Called when an entire binary frame has been received.final void
onWebsocketOpen
(WebSocket conn, Handshakedata handshake) Called after onHandshakeReceived returns true.final void
This method is used to inform the selector thread that there is data queued to be written to the socket.private void
pushBuffer
(ByteBuffer buf) protected void
queue
(WebSocketImpl ws) protected void
protected boolean
This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronizedvoid
run()
void
setDaemon
(boolean daemon) Setter for daemonvoid
setMaxPendingConnections
(int numberOfConnections) Set the requested maximum number of pending connections on the socket.final void
void
start()
Starts the server selectorthread that binds to the currently set port number and listeners for WebSocket connection requests.void
stop()
void
stop
(int timeout) void
Closes all connected clients sockets, then closes the underlying ServerSocketChannel, effectively killing the server socket selectorthread, freeing the port the server was bound to and stops all internal workerthreads.private ByteBuffer
Methods inherited from class org.java_websocket.AbstractWebSocket
getConnectionLostTimeout, getReceiveBufferSize, isDaemon, isReuseAddr, isTcpNoDelay, setConnectionLostTimeout, setReceiveBufferSize, setReuseAddr, setTcpNoDelay, startConnectionLostTimer, stopConnectionLostTimer
Methods inherited from class org.java_websocket.WebSocketAdapter
onPreparePing, onWebsocketHandshakeReceivedAsClient, onWebsocketHandshakeReceivedAsServer, onWebsocketHandshakeSentAsClient, onWebsocketPing, onWebsocketPong
-
Field Details
-
AVAILABLE_PROCESSORS
private static final int AVAILABLE_PROCESSORS -
log
private final org.slf4j.Logger logLogger instance- Since:
- 1.4.0
-
connections
Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete and socket can be written to, or read from. -
address
The port number that this WebSocket server should listen on. Default is WebSocketImpl.DEFAULT_PORT. -
server
The socket channel for this WebSocket server. -
selector
The 'Selector' used to get event keys from the underlying socket. -
drafts
The Draft of the WebSocket protocol the Server is adhering to. -
selectorthread
-
isclosed
-
decoders
-
iqueue
-
buffers
-
queueinvokes
private int queueinvokes -
queuesize
-
wsf
-
maxPendingConnections
private int maxPendingConnectionsAttribute which allows you to configure the socket "backlog" parameter which determines how many client connections can be queued.- Since:
- 1.5.0
-
-
Constructor Details
-
WebSocketServer
public WebSocketServer()Creates a WebSocketServer that will attempt to listen on port WebSocketImpl.DEFAULT_PORT.- See Also:
-
WebSocketServer
Creates a WebSocketServer that will attempt to bind/listen on the given address.- Parameters:
address
- The address to listen to- See Also:
-
WebSocketServer
- Parameters:
address
- The address (host:port) this server should listen on.decodercount
- The number ofWebSocketServer.WebSocketWorker
s that will be used to process the incoming network data. By default this will beRuntime.getRuntime().availableProcessors()
- See Also:
-
WebSocketServer
- Parameters:
address
- The address (host:port) this server should listen on.drafts
- The versions of the WebSocket protocol that this server instance should comply to. Clients that use an other protocol version will be rejected.- See Also:
-
WebSocketServer
- Parameters:
address
- The address (host:port) this server should listen on.decodercount
- The number ofWebSocketServer.WebSocketWorker
s that will be used to process the incoming network data. By default this will beRuntime.getRuntime().availableProcessors()
drafts
- The versions of the WebSocket protocol that this server instance should comply to. Clients that use an other protocol version will be rejected.- See Also:
-
WebSocketServer
- Parameters:
existingChannel
- An already open and bound server socket channel, which this server will use. For example, it can be System.inheritedChannel() to implement socket activation.
-
WebSocketServer
public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts, Collection<WebSocket> connectionscontainer) Creates a WebSocketServer that will attempt to bind/listen on the given address, and comply withDraft
version draft.- Parameters:
address
- The address (host:port) this server should listen on.decodercount
- The number ofWebSocketServer.WebSocketWorker
s that will be used to process the incoming network data. By default this will beRuntime.getRuntime().availableProcessors()
drafts
- The versions of the WebSocket protocol that this server instance should comply to. Clients that use an other protocol version will be rejected.connectionscontainer
- Allows to specify a collection that will be used to store the websockets in.
If you plan to often iterate through the currently connected websockets you may want to use a collection that does not require synchronization like aCopyOnWriteArraySet
. In that case make sure that you overloadremoveConnection(WebSocket)
andaddConnection(WebSocket)
.
By default aHashSet
will be used.- See Also:
-
-
Method Details
-
checkAddressOfExistingChannel
-
start
public void start()Starts the server selectorthread that binds to the currently set port number and listeners for WebSocket connection requests. Creates a fixed thread pool with the sizeAVAILABLE_PROCESSORS
May only be called once.Alternatively you can call
run()
directly.- Throws:
IllegalStateException
- Starting an instance again
-
stop
- Throws:
InterruptedException
-
stop
Closes all connected clients sockets, then closes the underlying ServerSocketChannel, effectively killing the server socket selectorthread, freeing the port the server was bound to and stops all internal workerthreads.If this method is called before the server is started it will never start.
- Parameters:
timeout
- Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking.closeMessage
- Specifies message for remote client- Throws:
InterruptedException
- Interrupt
-
stop
- Throws:
InterruptedException
-
getConnections
Returns all currently connected clients. This collection does not allow any modification e.g. removing a client.- Specified by:
getConnections
in classAbstractWebSocket
- Returns:
- A unmodifiable collection of all currently connected clients
- Since:
- 1.3.8
-
getAddress
-
getPort
public int getPort()Gets the port number that this server listens on.- Returns:
- The port number.
-
setDaemon
public void setDaemon(boolean daemon) Description copied from class:AbstractWebSocket
Setter for daemonControls whether or not internal threads are spawned in daemon mode
- Overrides:
setDaemon
in classAbstractWebSocket
-
getDraft
Get the list of active drafts- Returns:
- the available drafts for this server
-
setMaxPendingConnections
public void setMaxPendingConnections(int numberOfConnections) Set the requested maximum number of pending connections on the socket. The exact semantics are implementation specific. The value provided should be greater than 0. If it is less than or equal to 0, then an implementation specific default will be used. This option will be passed as "backlog" parameter toServerSocket.bind(SocketAddress, int)
- Parameters:
numberOfConnections
- the new number of allowed pending connections- Since:
- 1.5.0
-
getMaxPendingConnections
public int getMaxPendingConnections()Returns the currently configured maximum number of pending connections.- Returns:
- the maximum number of pending connections
- Since:
- 1.5.0
- See Also:
-
run
public void run() -
doAdditionalRead
Do an additional read- Throws:
InterruptedException
- thrown by taking a bufferIOException
- if an error happened during read
-
doAccept
private void doAccept(SelectionKey key, Iterator<SelectionKey> i) throws IOException, InterruptedException Execute a accept operation- Parameters:
key
- the selectionkey to read offi
- the iterator for the selection keys- Throws:
InterruptedException
- thrown by taking a bufferIOException
- if an error happened during accept
-
doRead
private boolean doRead(SelectionKey key, Iterator<SelectionKey> i) throws InterruptedException, WrappedIOException Execute a read operation- Parameters:
key
- the selectionkey to read offi
- the iterator for the selection keys- Returns:
- true, if the read was successful, or false if there was an error
- Throws:
InterruptedException
- thrown by taking a bufferIOException
- if an error happened during readWrappedIOException
-
doWrite
Execute a write operation- Parameters:
key
- the selectionkey to write on- Throws:
IOException
- if an error happened during batchWrappedIOException
-
doSetupSelectorAndServerThread
private boolean doSetupSelectorAndServerThread()Setup the selector thread as well as basic server settings- Returns:
- true, if everything was successful, false if some error happened
-
doEnsureSingleThread
private boolean doEnsureSingleThread()The websocket server can only be started once- Returns:
- true, if the server can be started, false if already a thread is running
-
doServerShutdown
private void doServerShutdown()Clean up everything after a shutdown -
allocateBuffers
- Throws:
InterruptedException
-
releaseBuffers
- Throws:
InterruptedException
-
createBuffer
-
queue
- Throws:
InterruptedException
-
takeBuffer
- Throws:
InterruptedException
-
pushBuffer
- Throws:
InterruptedException
-
handleIOException
-
handleFatal
-
onWebsocketMessage
Description copied from interface:WebSocketListener
Called when an entire text frame has been received. Do whatever you want here...- Specified by:
onWebsocketMessage
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring on.message
- The UTF-8 decoded message that was received.
-
onWebsocketMessage
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
- TheWebSocket
instance this event is occurring on.blob
- The binary message that was received.
-
onWebsocketOpen
Description copied from interface:WebSocketListener
Called after onHandshakeReceived returns true. Indicates that a complete WebSocket connection has been established, and we are ready to send/receive data.- Specified by:
onWebsocketOpen
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring on.handshake
- The handshake of the websocket instance
-
onWebsocketClose
Description copied from interface:WebSocketListener
Called afterWebSocket#close
is explicity called, or when the other end of the WebSocket connection is closed.- Specified by:
onWebsocketClose
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring 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.
-
removeConnection
This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronizedWebSocketServer(InetSocketAddress, int, List, Collection)
allows to specify a collection which will be used to store current connections in.
Depending on the type on the connection, modifications of that collection may have to be synchronized.- Parameters:
ws
- The Websocket connection which should be removed- Returns:
- Removing connection successful
-
addConnection
- Parameters:
ws
- the Websocket connection which should be added- Returns:
- Adding connection successful
- See Also:
-
onWebsocketError
Description copied from interface:WebSocketListener
Called if an exception worth noting occurred. If an error causes the connection to fail onClose will be called additionally afterwards.- Specified by:
onWebsocketError
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring 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
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:
w
- TheWebSocket
instance this event is occurring on.
-
onWebsocketCloseInitiated
Description copied from interface:WebSocketListener
send when this peer sends a close handshake- Specified by:
onWebsocketCloseInitiated
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring on.code
- The codes can be looked up here:CloseFrame
reason
- Additional information string
-
onWebsocketClosing
Description copied from interface:WebSocketListener
Called as soon as no further frames are accepted- Specified by:
onWebsocketClosing
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring 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
-
onClosing
-
setWebSocketFactory
-
getWebSocketFactory
-
onConnect
Returns whether a new connection shall be accepted or not.
Therefore method is well suited to implement some kind of connection limitation.- Parameters:
key
- the SelectionKey for the new connection- Returns:
- Can this new connection be accepted
- See Also:
-
getSocket
Getter to return the socket used by this specific connection- Parameters:
conn
- The specific connection- Returns:
- The socket used by this connection
-
getLocalSocketAddress
- Specified by:
getLocalSocketAddress
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring on.- Returns:
- Returns the address of the endpoint this socket is bound to.
- See Also:
-
getRemoteSocketAddress
- Specified by:
getRemoteSocketAddress
in interfaceWebSocketListener
- Parameters:
conn
- TheWebSocket
instance this event is occurring on.- Returns:
- Returns the address of the endpoint this socket is connected to, or
null
if it is unconnected. - See Also:
-
onOpen
Called after an opening handshake has been performed and the given websocket is ready to be written on.- Parameters:
conn
- TheWebSocket
instance this event is occurring on.handshake
- The handshake of the websocket instance
-
onClose
Called after the websocket connection has been closed.- Parameters:
conn
- TheWebSocket
instance this event is occurring 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.
-
onMessage
Callback for string messages received from the remote host- Parameters:
conn
- TheWebSocket
instance this event is occurring on.message
- The UTF-8 decoded message that was received.- See Also:
-
onError
Called when errors occurs. If an error causes the websocket connection to failonClose(WebSocket, 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:
conn
- Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound.ex
- The exception causing this error
-
onStart
public abstract void onStart()Called when the server started up successfully.If any error occurred, onError is called instead.
-
onMessage
Callback for binary messages received from the remote host- Parameters:
conn
- TheWebSocket
instance this event is occurring on.message
- The binary message that was received.- See Also:
-
broadcast
Send a text to all connected endpoints- Parameters:
text
- the text to send to the endpoints
-
broadcast
public void broadcast(byte[] data) Send a byte array to all connected endpoints- Parameters:
data
- the data to send to the endpoints
-
broadcast
Send a ByteBuffer to all connected endpoints- Parameters:
data
- the data to send to the endpoints
-
broadcast
Send a byte array to a specific collection of websocket connections- Parameters:
data
- the data to send to the endpointsclients
- a collection of endpoints to whom the text has to be send
-
broadcast
Send a ByteBuffer to a specific collection of websocket connections- Parameters:
data
- the data to send to the endpointsclients
- a collection of endpoints to whom the text has to be send
-
broadcast
Send a text to a specific collection of websocket connections- Parameters:
text
- the text to send to the endpointsclients
- a collection of endpoints to whom the text has to be send
-
doBroadcast
Private method to cache all the frames to improve memory footprint and conversion time- Parameters:
data
- the data to broadcastclients
- the clients to send the message to
-
fillFrames
private void fillFrames(Draft draft, Map<Draft, List<Framedata>> draftFrames, String strData, ByteBuffer byteData) Fills the draftFrames with new data for the broadcast- Parameters:
draft
- The draft to usedraftFrames
- The list of frames per draft to fillstrData
- the string data, can be nullbyteData
- the byte buffer data, can be null
-