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
- Direct Known Subclasses:
WsServer
public abstract class WebSocketServer extends AbstractWebSocket implements Runnable
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 Classes Modifier and Type Class Description classWebSocketServer.WebSocketWorkerThis class is used to process incoming data
-
Field Summary
Fields Modifier and Type Field Description protected List<WebSocketServer.WebSocketWorker>decodersstatic intDECODERS
-
Constructor Summary
Constructors Constructor Description WebSocketServer()Creates a WebSocketServer that will attempt to listen on port WebSocket.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 with Draft version draft.WebSocketServer(InetSocketAddress address, List<Draft> drafts)
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected booleanaddConnection(WebSocket ws)protected voidallocateBuffers(WebSocket c)voidbroadcast(byte[] data)Send a byte array to all connected endpointsvoidbroadcast(byte[] data, Collection<WebSocket> clients)Send a byte array to a specific collection of websocket connectionsvoidbroadcast(String text)Send a text to all connected endpointsvoidbroadcast(String text, Collection<WebSocket> clients)Send a text to a specific collection of websocket connectionsvoidbroadcast(ByteBuffer data)Send a ByteBuffer to all connected endpointsvoidbroadcast(ByteBuffer data, Collection<WebSocket> clients)Send a ByteBuffer to a specific collection of websocket connectionsCollection<WebSocket>connections()Deprecated.ByteBuffercreateBuffer()InetSocketAddressgetAddress()Collection<WebSocket>getConnections()Returns all currently connected clients.List<Draft>getDraft()InetSocketAddressgetLocalSocketAddress(WebSocket conn)intgetPort()Gets the port number that this server listens on.InetSocketAddressgetRemoteSocketAddress(WebSocket conn)WebSocketFactorygetWebSocketFactory()abstract voidonClose(WebSocket conn, int code, String reason, boolean remote)Called after the websocket connection has been closed.voidonCloseInitiated(WebSocket conn, int code, String reason)voidonClosing(WebSocket conn, int code, String reason, boolean remote)protected booleanonConnect(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 voidonError(WebSocket conn, Exception ex)Called when errors occurs.voidonFragment(WebSocket conn, Framedata fragment)Deprecated.abstract voidonMessage(WebSocket conn, String message)Callback for string messages received from the remote hostvoidonMessage(WebSocket conn, ByteBuffer message)Callback for binary messages received from the remote hostabstract voidonOpen(WebSocket conn, ClientHandshake handshake)Called after an opening handshake has been performed and the given websocket is ready to be written on.abstract voidonStart()Called when the server started up successfully.voidonWebsocketClose(WebSocket conn, int code, String reason, boolean remote)Called after WebSocket#close is explicity called, or when the other end of the WebSocket connection is closed.voidonWebsocketCloseInitiated(WebSocket conn, int code, String reason)send when this peer sends a close handshakevoidonWebsocketClosing(WebSocket conn, int code, String reason, boolean remote)Called as soon as no further frames are acceptedvoidonWebsocketError(WebSocket conn, Exception ex)Called if an exception worth noting occurred.ServerHandshakeBuilderonWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, ClientHandshake request)This default implementation does not do anything.voidonWebsocketMessage(WebSocket conn, String message)Called when an entire text frame has been received.voidonWebsocketMessage(WebSocket conn, ByteBuffer blob)Called when an entire binary frame has been received.voidonWebsocketMessageFragment(WebSocket conn, Framedata frame)Deprecated.voidonWebsocketOpen(WebSocket conn, Handshakedata handshake)Called after onHandshakeReceived returns true.voidonWriteDemand(WebSocket w)This method is used to inform the selector thread that there is data queued to be written to the socket.protected voidqueue(WebSocketImpl ws)protected voidreleaseBuffers(WebSocket c)protected booleanremoveConnection(WebSocket ws)This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronizedvoidrun()voidsetWebSocketFactory(WebSocketServerFactory wsf)voidstart()Starts the server selectorthread that binds to the currently set port number and listeners for WebSocket connection requests.voidstop()voidstop(int timeout)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.-
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, onWebsocketHandshakeSentAsClient, onWebsocketPing, onWebsocketPong
-
-
-
-
Field Detail
-
DECODERS
public static int DECODERS
-
decoders
protected List<WebSocketServer.WebSocketWorker> decoders
-
-
Constructor Detail
-
WebSocketServer
public WebSocketServer()
Creates a WebSocketServer that will attempt to listen on port WebSocket.DEFAULT_PORT.- See Also:
more details here
-
WebSocketServer
public WebSocketServer(InetSocketAddress address)
Creates a WebSocketServer that will attempt to bind/listen on the given address.- Parameters:
address- The address to listen to- See Also:
more details here
-
WebSocketServer
public WebSocketServer(InetSocketAddress address, int decodercount)
- Parameters:
address- The address (host:port) this server should listen on.decodercount- The number ofWebSocketServer.WebSocketWorkers that will be used to process the incoming network data. By default this will beRuntime.getRuntime().availableProcessors()- See Also:
more details here
-
WebSocketServer
public WebSocketServer(InetSocketAddress address, List<Draft> drafts)
- 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:
more details here
-
WebSocketServer
public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts)
- Parameters:
address- The address (host:port) this server should listen on.decodercount- The number ofWebSocketServer.WebSocketWorkers 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:
more details here
-
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 with Draft version draft.- Parameters:
address- The address (host:port) this server should listen on.decodercount- The number ofWebSocketServer.WebSocketWorkers 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 aHashSetwill be used.- See Also:
for more control over syncronized operation, more about drafts
-
-
Method Detail
-
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 sizeDECODERS
May only be called once. Alternatively you can callrun()directly.- Throws:
IllegalStateException- Starting an instance again
-
stop
public void stop(int timeout) throws InterruptedExceptionCloses 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.- Throws:
InterruptedException- Interrupt
-
stop
public void stop() throws IOException, InterruptedException- Throws:
IOExceptionInterruptedException
-
connections
@Deprecated public Collection<WebSocket> connections()
Deprecated.PLEASE use the method getConnections() in the future! Returns a WebSocket[] of currently connected clients. Its iterators will be failfast and its not judicious to modify it.- Returns:
- The currently connected clients.
-
getConnections
public Collection<WebSocket> getConnections()
Returns all currently connected clients. This collection does not allow any modification e.g. removing a client.- Specified by:
getConnectionsin classAbstractWebSocket- Returns:
- A unmodifiable collection of all currently connected clients
- Since:
- 1.3.8
-
getAddress
public InetSocketAddress getAddress()
-
getPort
public int getPort()
Gets the port number that this server listens on.- Returns:
- The port number.
-
allocateBuffers
protected void allocateBuffers(WebSocket c) throws InterruptedException
- Throws:
InterruptedException
-
releaseBuffers
protected void releaseBuffers(WebSocket c) throws InterruptedException
- Throws:
InterruptedException
-
createBuffer
public ByteBuffer createBuffer()
-
queue
protected void queue(WebSocketImpl ws) throws InterruptedException
- Throws:
InterruptedException
-
onWebsocketMessage
public final void onWebsocketMessage(WebSocket conn, String message)
Description copied from interface:WebSocketListenerCalled when an entire text frame has been received. Do whatever you want here...- Specified by:
onWebsocketMessagein interfaceWebSocketListener- Parameters:
conn- The WebSocket instance this event is occurring on.message- The UTF-8 decoded message that was received.
-
onWebsocketMessageFragment
@Deprecated public void onWebsocketMessageFragment(WebSocket conn, Framedata frame)
Deprecated.Description copied from class:WebSocketAdapterThis default implementation does not do anything. Go ahead and overwrite it- Specified by:
onWebsocketMessageFragmentin interfaceWebSocketListener- Overrides:
onWebsocketMessageFragmentin classWebSocketAdapter- Parameters:
conn- The WebSocket instance this event is occurring on.frame- The fragmented frame- See Also:
WebSocketListener.onWebsocketMessageFragment(WebSocket, Framedata)
-
onWebsocketMessage
public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob)
Description copied from interface:WebSocketListenerCalled when an entire binary frame has been received. Do whatever you want here...- Specified by:
onWebsocketMessagein interfaceWebSocketListener- Parameters:
conn- The WebSocket instance this event is occurring on.blob- The binary message that was received.
-
onWebsocketOpen
public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake)
Description copied from interface:WebSocketListenerCalled after onHandshakeReceived returns true. Indicates that a complete WebSocket connection has been established, and we are ready to send/receive data.- Specified by:
onWebsocketOpenin 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)
Description copied from interface:WebSocketListenerCalled after WebSocket#close is explicity called, or when the other end of the WebSocket connection is closed.- Specified by:
onWebsocketClosein interfaceWebSocketListener- Parameters:
conn- The WebSocket instance this event is occuring on.code- The codes can be looked up here:CloseFramereason- Additional information stringremote- Returns whether or not the closing of the connection was initiated by the remote host.
-
removeConnection
protected boolean removeConnection(WebSocket ws)
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 Webscoket connection which should be removed- Returns:
- Removing connection successful
-
onWebsocketHandshakeReceivedAsServer
public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException
Description copied from class:WebSocketAdapterThis default implementation does not do anything. Go ahead and overwrite it.- Specified by:
onWebsocketHandshakeReceivedAsServerin interfaceWebSocketListener- Overrides:
onWebsocketHandshakeReceivedAsServerin classWebSocketAdapter- Parameters:
conn- The WebSocket related to this eventdraft- The protocol draft the client uses to connectrequest- The opening http message send by the client. Can be used to access additional fields like cookies.- Returns:
- Returns an incomplete handshake containing all optional fields
- Throws:
InvalidDataException- Throwing this exception will cause this handshake to be rejected- See Also:
WebSocketListener.onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)
-
addConnection
protected boolean addConnection(WebSocket ws)
- Parameters:
ws- the Webscoket connection which should be added- Returns:
- Adding connection successful
- See Also:
removeConnection(WebSocket)
-
onWebsocketError
public final void onWebsocketError(WebSocket conn, Exception ex)
Description copied from interface:WebSocketListenerCalled if an exception worth noting occurred. If an error causes the connection to fail onClose will be called additionally afterwards.- Specified by:
onWebsocketErrorin 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 w)
Description copied from interface:WebSocketListenerThis method is used to inform the selector thread that there is data queued to be written to the socket.- Specified by:
onWriteDemandin interfaceWebSocketListener- Parameters:
w- The WebSocket instance this event is occuring on.
-
onWebsocketCloseInitiated
public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason)
Description copied from interface:WebSocketListenersend when this peer sends a close handshake- Specified by:
onWebsocketCloseInitiatedin interfaceWebSocketListener- Parameters:
conn- The WebSocket instance this event is occuring on.code- The codes can be looked up here:CloseFramereason- Additional information string
-
onWebsocketClosing
public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote)
Description copied from interface:WebSocketListenerCalled as soon as no further frames are accepted- Specified by:
onWebsocketClosingin interfaceWebSocketListener- Parameters:
conn- The WebSocket instance this event is occuring on.code- The codes can be looked up here:CloseFramereason- Additional information stringremote- Returns whether or not the closing of the connection was initiated by the remote host.
-
setWebSocketFactory
public final void setWebSocketFactory(WebSocketServerFactory wsf)
-
getWebSocketFactory
public final WebSocketFactory getWebSocketFactory()
-
onConnect
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.- Parameters:
key- the SelectionKey for the new connection- Returns:
- Can this new connection be accepted
- See Also:
onOpen(WebSocket, ClientHandshake),onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)
-
getLocalSocketAddress
public InetSocketAddress getLocalSocketAddress(WebSocket conn)
- Specified by:
getLocalSocketAddressin 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:
getRemoteSocketAddressin interfaceWebSocketListener- Parameters:
conn- The WebSocket instance this event is occuring on.- Returns:
- Returns the address of the endpoint this socket is connected to, or
nullif it is unconnected. - See Also:
WebSocket.getRemoteSocketAddress()
-
onOpen
public abstract void onOpen(WebSocket conn, ClientHandshake handshake)
Called after an opening handshake has been performed and the given websocket is ready to be written on.- Parameters:
conn- The WebSocket instance this event is occuring on.handshake- The handshake of the websocket instance
-
onClose
public abstract void onClose(WebSocket conn, int code, String reason, boolean remote)
Called after the websocket connection has been closed.- Parameters:
conn- The WebSocket instance this event is occuring on.code- The codes can be looked up here:CloseFramereason- Additional information stringremote- Returns whether or not the closing of the connection was initiated by the remote host.
-
onMessage
public abstract void onMessage(WebSocket conn, String message)
Callback for string messages received from the remote host- Parameters:
conn- The WebSocket instance this event is occuring on.message- The UTF-8 decoded message that was received.- See Also:
onMessage(WebSocket, ByteBuffer)
-
onError
public abstract void onError(WebSocket conn, Exception ex)
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 occured, onError is called instead.
-
onMessage
public void onMessage(WebSocket conn, ByteBuffer message)
Callback for binary messages received from the remote host- Parameters:
conn- The WebSocket instance this event is occurring on.message- The binary message that was received.- See Also:
onMessage(WebSocket, ByteBuffer)
-
onFragment
@Deprecated public void onFragment(WebSocket conn, Framedata fragment)
Deprecated.Callback for fragmented frames- Parameters:
conn- The WebSocket instance this event is occurring on.fragment- The fragmented frame- See Also:
WebSocket.sendFragmentedFrame(org.java_websocket.framing.Framedata.Opcode, ByteBuffer, boolean)
-
broadcast
public void broadcast(String text)
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
public void broadcast(ByteBuffer data)
Send a ByteBuffer to all connected endpoints- Parameters:
data- the data to send to the endpoints
-
broadcast
public void broadcast(byte[] data, Collection<WebSocket> clients)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
public void broadcast(ByteBuffer data, Collection<WebSocket> clients)
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
public void broadcast(String text, Collection<WebSocket> clients)
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
-
-