This chapter tells how to use GNU WebSocket4J in a server application.
Throughout this chapter WebServerSocket will refer to
websocket4j.server.WebServerSocket class and WebSocket
will refer to websocket4j.server.WebSocket class.
Accepting WebSocket connections is similar to using TCP sockets from the
standard library. You have to create an instance of
WebServerSocket (modelled after java.net.ServerSocket),
and then you can use accept() : WebSocket method to get incoming
connections. Accepted sockets have successfully completed an opening
handshake and are ready to use (see Using an established socket).
websocket4j.server.WebServerSocket has two constructors, first
without any parameters and second taking an Integer. Second one
creates a new socket listening on port specified as an argument, and the
first one chooses a random free port. If you create a socket listening
on a random port, you can use getLocalPort() : Integer method to get that
port number.
accept() : WebSocket works similar to method, of
java.net.ServerSocket class, of the same name. It waits until
someone connects and returns an established socket. You can limit the
time for which accept will block with setSoTimeout(Integer)
: void method (provided Integer is time in milliseconds) — if
no client connects in this much time a java.io.IOException will
be thrown.
After you've accepted a socket, you can use getRequestUri() :
String method of WebSocket to get URI requested by client, so
you can decide what to do next with this socket.
Both WebServerSocket and WebSocket have close() :
void method that closes the socket and ends connection in case of
WebSocket, or stops listening for new connections in case of
WebServerSocket. isClosed() : Boolean method can be used
to determine if socket is already closed.