This chapter tells how to use GNU WebSocket4J in a client application.
Throughout this chapter WebSocket
will refer to
websocket4j.client.WebSocket
class.
WebSocket
class works similar to java.net.Socket
— you
have to create an instance providing information where it should connect
to and you get back a socket that is ready to use (see Using an established socket).
WebSocket
has two constructors, first one takes a String
,
Integer
and String
, second one takes an additional
Integer
. First String
is the host name of the server you
want to connect to, first Integer
is port on which the server
listens for incoming connections. Second String
is URI that
should be requested when connecting — just as HTTP servers, WebSocket
servers can handle multiple kinds of connections over one port.
For example new WebSocket("localhost", 5432, "/echo")
would
connect to localhost on port 5432 and request /echo URI. In JavaScript
API you'd use ws://localhost:5432/echo
URI to connect to the same
server.
Fourth, optional, argument of the constructor is timeout in milliseconds, if the opening handshake takes more time than this, an IOException will be thrown.
Just like the server socket, client sockets have close() : void
method that ends the connection. Also you can use isClosed() :
Boolean
method to check if the socket is already closed.