org.java_websocket.server
Class WebSocketServer

java.lang.Object
  extended by org.java_websocket.WebSocketAdapter
      extended by org.java_websocket.server.WebSocketServer
All Implemented Interfaces:
Runnable, WebSocketListener

public abstract class WebSocketServer
extends WebSocketAdapter
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
static interface WebSocketServer.WebSocketServerFactory
           
 class WebSocketServer.WebSocketWorker
           
 
Field Summary
static int DECODERS
           
 
Constructor Summary
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 decoders)
           
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
protected  boolean addConnection(WebSocket ws)
           
protected  void allocateBuffers(WebSocket c)
           
 Collection<WebSocket> connections()
          Returns a WebSocket[] of currently connected clients.
 ByteBuffer createBuffer()
           
 InetSocketAddress getAddress()
           
 List<Draft> getDraft()
           
protected  String getFlashSecurityPolicy()
          Gets the XML string that should be returned if a client requests a Flash security policy.
 InetSocketAddress getLocalSocketAddress(WebSocket conn)
           
 int getPort()
          Gets the port number that this server listens on.
 InetSocketAddress getRemoteSocketAddress(WebSocket conn)
           
 WebSocketFactory getWebSocketFactory()
           
abstract  void onClose(WebSocket conn, int code, String reason, boolean remote)
          Called after the websocket connection has been closed.
 void onCloseInitiated(WebSocket conn, int code, String reason)
           
 void onClosing(WebSocket conn, int code, String reason, boolean remote)
           
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 onError(WebSocket conn, Exception ex)
          Called when errors occurs.
 void onMessage(WebSocket conn, ByteBuffer message)
          Callback for binary messages received from the remote host
abstract  void onMessage(WebSocket conn, String message)
          Callback for string messages received from the remote host
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.
 void onWebsocketClose(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.
 void onWebsocketCloseInitiated(WebSocket conn, int code, String reason)
          send when this peer sends a close handshake
 void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote)
          called as soon as no further frames are accepted
 void onWebsocketError(WebSocket conn, Exception ex)
          Called if an exception worth noting occurred.
 void onWebsocketMessage(WebSocket conn, ByteBuffer blob)
          Called when an entire binary frame has been received.
 void onWebsocketMessage(WebSocket conn, String message)
          Called when an entire text frame has been received.
 void onWebsocketOpen(WebSocket conn, Handshakedata handshake)
          Called after onHandshakeReceived returns true.
 void onWriteDemand(WebSocket w)
          This method is used to inform the selector thread that there is data queued to be written to the socket.
protected  void releaseBuffers(WebSocket c)
           
protected  boolean removeConnection(WebSocket ws)
          This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized
 void run()
           
 void setWebSocketFactory(WebSocketServer.WebSocketServerFactory wsf)
           
 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)
          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.WebSocketAdapter
getFlashPolicy, onWebsocketHandshakeReceivedAsClient, onWebsocketHandshakeReceivedAsServer, onWebsocketHandshakeSentAsClient, onWebsocketMessageFragment, onWebsocketPing, onWebsocketPong
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DECODERS

public static int DECODERS
Constructor Detail

WebSocketServer

public WebSocketServer()
                throws UnknownHostException
Creates a WebSocketServer that will attempt to listen on port WebSocket.DEFAULT_PORT.

Throws:
UnknownHostException
See Also:
more details here

WebSocketServer

public WebSocketServer(InetSocketAddress address)
Creates a WebSocketServer that will attempt to bind/listen on the given address.

See Also:
more details here

WebSocketServer

public WebSocketServer(InetSocketAddress address,
                       int decoders)
See Also:
more details here

WebSocketServer

public WebSocketServer(InetSocketAddress address,
                       List<Draft> drafts)
See Also:
more details here

WebSocketServer

public WebSocketServer(InetSocketAddress address,
                       int decodercount,
                       List<Draft> drafts)
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 of WebSocketServer.WebSocketWorkers that will be used to process the incoming network data. By default this will be Runtime.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 a CopyOnWriteArraySet. In that case make sure that you overload removeConnection(WebSocket) and addConnection(WebSocket).
By default a HashSet will 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 size DECODERS
May only be called once. Alternatively you can call run() directly.

Throws:
IllegalStateException

stop

public void stop(int timeout)
          throws IOException,
                 InterruptedException
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 shall pass between initiating the close handshakes with the connected clients and closing the servers socket channel.
Throws:
IOException - When ServerSocketChannel.close throws an IOException
InterruptedException

stop

public void stop()
          throws IOException,
                 InterruptedException
Throws:
IOException
InterruptedException

connections

public Collection<WebSocket> connections()
Returns a WebSocket[] of currently connected clients. Its iterators will be failfast and its not judicious to modify it.

Returns:
The currently connected clients.

getAddress

public InetSocketAddress getAddress()

getPort

public int getPort()
Gets the port number that this server listens on.

Returns:
The port number.

getDraft

public List<Draft> getDraft()

run

public void run()
Specified by:
run in interface Runnable

allocateBuffers

protected void allocateBuffers(WebSocket c)
                        throws InterruptedException
Throws:
InterruptedException

releaseBuffers

protected void releaseBuffers(WebSocket c)
                       throws InterruptedException
Throws:
InterruptedException

createBuffer

public ByteBuffer createBuffer()

getFlashSecurityPolicy

protected String getFlashSecurityPolicy()
Gets the XML string that should be returned if a client requests a Flash security policy. The default implementation allows access from all remote domains, but only on the port that this WebSocketServer is listening on. This is specifically implemented for gitime's WebSocket client for Flash: http://github.com/gimite/web-socket-js

Returns:
An XML String that comforms to Flash's security policy. You MUST not include the null char at the end, it is appended automatically.

onWebsocketMessage

public final void onWebsocketMessage(WebSocket conn,
                                     String message)
Description copied from interface: WebSocketListener
Called when an entire text frame has been received. Do whatever you want here...

Specified by:
onWebsocketMessage in interface WebSocketListener
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 interface WebSocketListener
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: 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 interface WebSocketListener
Parameters:
conn - The WebSocket instance this event is occuring on.

onWebsocketClose

public final void onWebsocketClose(WebSocket conn,
                                   int code,
                                   String reason,
                                   boolean remote)
Description copied from interface: WebSocketListener
Called after WebSocket#close is explicity called, or when the other end of the WebSocket connection is closed.

Specified by:
onWebsocketClose in interface WebSocketListener

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


addConnection

protected boolean addConnection(WebSocket ws)
See Also:
removeConnection(WebSocket)

onWebsocketError

public final void onWebsocketError(WebSocket conn,
                                   Exception ex)
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 interface WebSocketListener
Parameters:
conn - may be null if the error does not belong to a single connection
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: 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 interface WebSocketListener

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 interface WebSocketListener

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 interface WebSocketListener

onCloseInitiated

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

onClosing

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

setWebSocketFactory

public final void setWebSocketFactory(WebSocketServer.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.

See Also:
#onOpen(WebSocket, ClientHandshake)}, {@link #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)}

getLocalSocketAddress

public InetSocketAddress getLocalSocketAddress(WebSocket conn)
Specified by:
getLocalSocketAddress in interface WebSocketListener

getRemoteSocketAddress

public InetSocketAddress getRemoteSocketAddress(WebSocket conn)
Specified by:
getRemoteSocketAddress in interface WebSocketListener

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.


onClose

public abstract void onClose(WebSocket conn,
                             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 string
remote - 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

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 fail onClose(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:
con - Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound.

onMessage

public void onMessage(WebSocket conn,
                      ByteBuffer message)
Callback for binary messages received from the remote host

See Also:
onMessage(WebSocket, String)


Copyright © 2013 Pusher. All Rights Reserved.