Next: , Previous: WebSocket, Up: Top

2 Accepting connections

This chapter tells how to use GNU WebSocket4J in a server application.

Naming convention

Throughout this chapter WebServerSocket will refer to websocket4j.server.WebServerSocket class and WebSocket will refer to websocket4j.server.WebSocket class.

General idea

Accepting WebSocket connections is similar to using TCP sockets from the standard library. You have to create an instance of WebServerSocket (modelled after, 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).

Creating a WebServerSocket instance

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.

Accepting new connnections

accept() : WebSocket works similar to method, of 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 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.

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