Skip to content
Marcel Prestel edited this page Jan 3, 2018 · 2 revisions

Introduction

Attachments are a way for you as a developer to store data directly on a WebSocket instance.

You can use this for example to keep track of different clients or store authentication information in an easy way.

It is up to you, how to use it. There are no restraints given!

Example

This example shows you how to use this feature when you have a WebSocketServer, since it is the more common use case. But it also works for a WebSocketClient!

The method setAttachment() is used to attach any object to the specific WebSocket instance. This will overwrite the existing value!

The method getAttachment<T>() is used to retrieve the value. The currently saved attachment will be casted to T. This method does not check if the attachment is really of type T.

The default value is null.

Preamble

Let's assume we assign a specific index for each client. This index is set after the client connected to the server.

Later, we will use this index to determine which client closed the connection.

You can always access the attachment, this is just for this example!

Attaching an index during onOpen

@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
	conn.setAttachment( 1337 ); //Set the attachment to the current index
	index++;
}

In this example, the index is set the value 1337.

Accessing the index during onClose

@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
	int index = conn.<Integer>getAttachment(); // is 1337
	System.out.println( "ID " + index + " has left the room!");
}

This example will produce the following command line printout: ID 1337 has left the room!

You can also find the example here.