Top Description Inners Fields Constructors Methods
org.java_websocket.server

public abstract Class WebSocketServer

extends AbstractWebSocket
implements Runnable
Class Inheritance
All Implemented Interfaces
java.lang.Runnable
Imports
java.io.IOException, java.net.InetSocketAddress, .ServerSocket, .Socket, .SocketAddress, java.nio.ByteBuffer, java.nio.channels.CancelledKeyException, .ClosedByInterruptException, .SelectableChannel, .SelectionKey, .Selector, .ServerSocketChannel, .SocketChannel, java.util.ArrayList, .Collection, .Collections, .HashMap, .HashSet, .Iterator, .LinkedList, .List, .Map, .Set, java.util.concurrent.BlockingQueue, .CopyOnWriteArraySet, .LinkedBlockingQueue, java.util.concurrent.atomic.AtomicBoolean, .AtomicInteger, org.java_websocket.AbstractWebSocket, .SocketChannelIOHelper, .WebSocket, .WebSocketFactory, .WebSocketImpl, .WebSocketServerFactory, .WrappedByteChannel, org.java_websocket.drafts.Draft, org.java_websocket.exceptions.WebsocketNotConnectedException, .WrappedIOException, org.java_websocket.framing.CloseFrame, .Framedata, org.java_websocket.handshake.ClientHandshake, .Handshakedata, org.slf4j.Logger, .LoggerFactory

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 and Inner Type Summary

Modifier and TypeClass and Description
public class
WebSocketServer.WebSocketWorker

This class is used to process incoming data

Field Summary

Modifier and TypeField and Description
private final InetSocketAddress
address

The port number that this WebSocket server should listen on.

private static final int
private BlockingQueue<ByteBuffer>
private final Collection<WebSocket>
connections

Holds the list of active WebSocket connections.

protected List<WebSocketServer.WebSocketWorker>
private List<Draft>
drafts

The Draft of the WebSocket protocol the Server is adhering to.

private List<WebSocketImpl>
private final AtomicBoolean
private final Logger
private int
maxPendingConnections

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
selector

The 'Selector' used to get event keys from the underlying socket.

private Thread
private ServerSocketChannel
server

The socket channel for this WebSocket server.

private WebSocketServerFactory
Inherited from org.java_websocket.AbstractWebSocket:
DEFAULT_READ_BUFFER_SIZE

Constructor Summary

AccessConstructor and Description
public
WebSocketServer()

Creates a WebSocketServer that will attempt to listen on port WebSocketImpl.DEFAULT_PORT.

public
WebSocketServer(InetSocketAddress
The address to listen to
address
)

Creates a WebSocketServer that will attempt to bind/listen on the given address.

public
WebSocketServer(InetSocketAddress
The address (host:port) this server should listen on.
address
,
int
The number of WebSocketWorkers that will be used to process the incoming network data. By default this will be Runtime.getRuntime().availableProcessors()
decodercount
)

public
WebSocketServer(InetSocketAddress
The address (host:port) this server should listen on.
address
,
List<Draft>
The versions of the WebSocket protocol that this server instance should comply to. Clients that use an other protocol version will be rejected.
drafts
)

public
WebSocketServer(InetSocketAddress
The address (host:port) this server should listen on.
address
,
int
The number of WebSocketWorkers that will be used to process the incoming network data. By default this will be Runtime.getRuntime().availableProcessors()
decodercount
,
List<Draft>
The versions of the WebSocket protocol that this server instance should comply to. Clients that use an other protocol version will be rejected.
drafts
)

public
WebSocketServer(ServerSocketChannel
An already open and bound server socket channel, which this server will use. For example, it can be System.inheritedChannel() to implement socket activation.
existingChannel
)

public
WebSocketServer(InetSocketAddress
The address (host:port) this server should listen on.
address
,
int
The number of WebSocketWorkers that will be used to process the incoming network data. By default this will be Runtime.getRuntime().availableProcessors()
decodercount
,
List<Draft>
The versions of the WebSocket protocol that this server instance should comply to. Clients that use an other protocol version will be rejected.
drafts
,
Collection<WebSocket>
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 a CopyOnWriteArraySet. In that case make sure that you overload removeConnection(WebSocket) and addConnection(WebSocket).
By default a HashSet will be used.
connectionscontainer
)

Creates a WebSocketServer that will attempt to bind/listen on the given address, and comply with Draft version draft.

Method Summary

Modifier and TypeMethod and Description
protected boolean

Returns:

Adding connection successful
addConnection
(WebSocket
the Websocket connection which should be added
ws
)

protected void
public void
broadcast(String
the text to send to the endpoints
text
)

Send a text to all connected endpoints

public void
broadcast(byte[]
the data to send to the endpoints
data
)

Send a byte array to all connected endpoints

public void
broadcast(ByteBuffer
the data to send to the endpoints
data
)

Send a ByteBuffer to all connected endpoints

public void
broadcast(byte[]
the data to send to the endpoints
data
,
Collection<WebSocket>
a collection of endpoints to whom the text has to be send
clients
)

Send a byte array to a specific collection of websocket connections

public void
broadcast(ByteBuffer
the data to send to the endpoints
data
,
Collection<WebSocket>
a collection of endpoints to whom the text has to be send
clients
)

Send a ByteBuffer to a specific collection of websocket connections

public void
broadcast(String
the text to send to the endpoints
text
,
Collection<WebSocket>
a collection of endpoints to whom the text has to be send
clients
)

Send a text to a specific collection of websocket connections

private static InetSocketAddress
public ByteBuffer
private void
doAccept(SelectionKey
the selectionkey to read off
key
,
Iterator<SelectionKey>
the iterator for the selection keys
i
)

Execute a accept operation

private void
doAdditionalRead()

Do an additional read

private void
doBroadcast(Object
the data to broadcast
data
,
Collection<WebSocket>
the clients to send the message to
clients
)

Private method to cache all the frames to improve memory footprint and conversion time

private boolean

Returns:

true, if the server can be started, false if already a thread is running
doEnsureSingleThread
()

The websocket server can only be started once

private boolean

Returns:

true, if the read was successful, or false if there was an error
doRead
(SelectionKey
the selectionkey to read off
key
,
Iterator<SelectionKey>
the iterator for the selection keys
i
)

Execute a read operation

private void
doServerShutdown()

Clean up everything after a shutdown

private boolean

Returns:

true, if everything was successful, false if some error happened
doSetupSelectorAndServerThread
()

Setup the selector thread as well as basic server settings

private void
doWrite(SelectionKey
the selectionkey to write on
key
)

Execute a write operation

private void
fillFrames(Draft
The draft to use
draft
,
Map<Draft, List<Framedata>>
The list of frames per draft to fill
draftFrames
,
String
the string data, can be null
strData
,
ByteBuffer
the byte buffer data, can be null
byteData
)

Fills the draftFrames with new data for the broadcast

public InetSocketAddress
public Collection<WebSocket>

Returns:

A unmodifiable collection of all currently connected clients
getConnections
()

Implements abstract org.java_websocket.AbstractWebSocket.getConnections.

Returns all currently connected clients.

public List<Draft>

Returns:

the available drafts for this server
getDraft
()

Get the list of active drafts

public InetSocketAddress
public int

Returns:

the maximum number of pending connections
getMaxPendingConnections
()

Returns the currently configured maximum number of pending connections.

public int

Returns:

The port number.
getPort
()

Gets the port number that this server listens on.

public InetSocketAddress
private Socket

Returns:

The socket used by this connection
getSocket
(WebSocket
The specific connection
conn
)

Getter to return the socket used by this specific connection

public final WebSocketFactory
private void
private void
public abstract void
onClose(WebSocket
The WebSocket instance this event is occurring on.
conn
,
int
The codes can be looked up here: CloseFrame
code
,
String
Additional information string
reason
,
boolean
Returns whether or not the closing of the connection was initiated by the remote host.
remote
)

Called after the websocket connection has been closed.

public void
onCloseInitiated(WebSocket conn, int code, String reason)

public void
onClosing(WebSocket conn, int code, String reason, boolean remote)

protected boolean

Returns:

Can this new connection be accepted
onConnect
(SelectionKey
the SelectionKey for the new connection
key
)

Returns whether a new connection shall be accepted or not.

public abstract void
onError(WebSocket
Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound.
conn
,
Exception
The exception causing this error
ex
)

Called when errors occurs.

public abstract void
onMessage(WebSocket
The WebSocket instance this event is occurring on.
conn
,
String
The UTF-8 decoded message that was received.
message
)

Callback for string messages received from the remote host

public void
onMessage(WebSocket
The WebSocket instance this event is occurring on.
conn
,
ByteBuffer
The binary message that was received.
message
)

Callback for binary messages received from the remote host

public abstract void
onOpen(WebSocket
The WebSocket instance this event is occurring on.
conn
,
ClientHandshake
The handshake of the websocket instance
handshake
)

Called after an opening handshake has been performed and the given websocket is ready to be written on.

public abstract void
onStart()

Called when the server started up successfully.

public final void
onWebsocketClose(WebSocket conn, int code, String reason, boolean remote)

Implements org.java_websocket.WebSocketListener.onWebsocketClose.

Called after WebSocket#close is explicity called, or when the other end of the WebSocket connection is closed.

public void
onWebsocketCloseInitiated(WebSocket conn, int code, String reason)

Implements org.java_websocket.WebSocketListener.onWebsocketCloseInitiated.

send when this peer sends a close handshake

public void
onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote)

Implements org.java_websocket.WebSocketListener.onWebsocketClosing.

Called as soon as no further frames are accepted

public final void
onWebsocketError(WebSocket conn, Exception ex)

Implements org.java_websocket.WebSocketListener.onWebsocketError.

Called if an exception worth noting occurred.

public final void
onWebsocketMessage(WebSocket conn, String message)

Implements org.java_websocket.WebSocketListener.onWebsocketMessage.

Called when an entire text frame has been received.

public final void
onWebsocketMessage(WebSocket conn, ByteBuffer blob)

Implements org.java_websocket.WebSocketListener.onWebsocketMessage.

Called when an entire binary frame has been received.

public final void
onWebsocketOpen(WebSocket conn, Handshakedata handshake)

Implements org.java_websocket.WebSocketListener.onWebsocketOpen.

Called after onHandshakeReceived returns true.

public final void
onWriteDemand(WebSocket w)

Implements org.java_websocket.WebSocketListener.onWriteDemand.

This method is used to inform the selector thread that there is data queued to be written to the socket.

private void
protected void
protected void
protected boolean

Returns:

Removing connection successful
removeConnection
(WebSocket
The Websocket connection which should be removed
ws
)

This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized

WebSocketServer(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.

public void
run()

Implements java.lang.Runnable.run.

Runs this operation.

public void
setDaemon(boolean daemon)

Overrides org.java_websocket.AbstractWebSocket.setDaemon.

Setter for daemon

Controls whether or not internal threads are spawned in daemon mode

public void
setMaxPendingConnections(int
the new number of allowed pending connections
numberOfConnections
)

Set the requested maximum number of pending connections on the socket.

public final void
public void
start()

Starts the server selectorthread that binds to the currently set port number and listeners for WebSocket connection requests.

public void
stop(int timeout)

public void
stop(int
Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking.
timeout
,
String
Specifies message for remote client
closeMessage
)

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.

public void
stop()

private ByteBuffer
Inherited from org.java_websocket.AbstractWebSocket:
getConnectionLostTimeoutgetReceiveBufferSizeisDaemonisReuseAddrisTcpNoDelaysetConnectionLostTimeoutsetReceiveBufferSizesetReuseAddrsetTcpNoDelaystartConnectionLostTimerstopConnectionLostTimer