HTML and CSS Reference
In-Depth Information
public
class
ChatWebSocket
implements
WebSocket
.
OnTextMessage
{
private
Connection
connection
;
public
void
onOpen
(
Connection
connection
)
{
// Client (Browser) WebSockets has opened a connection.
// 1) Store the opened connection
this
.
connection
=
connection
;
// 2) Add ChatWebSocket in the global list of ChatWebSocket
// instances
// instance.
getWebsockets
().
add
(
this
);
}
public
void
onMessage
(
String
data
)
{
// Loop for each instance of ChatWebSocket to send message
// server to each client WebSockets.
try
{
for
(
ChatWebSocket
webSocket
:
getWebsockets
())
{
// send a message to the current client WebSocket.
webSocket
.
connection
.
sendMessage
(
data
);
}
}
catch
(
IOException
x
)
{
// Error was detected, close the ChatWebSocket client side
this
.
connection
.
disconnect
();
}
}
public
void
onClose
(
int
closeCode
,
String
message
)
{
// Remove ChatWebSocket in the global list of ChatWebSocket
// instance.
getWebsockets
().
remove
(
this
);
}
}
public
static
synchronized
Set
<
ChatWebSocket
>
getWebsockets
()
{
return
websockets
;
}
}
Next, we embed the Jetty WebSocket-capable server within the web application:
private
Server
server
=
null
;
/**
* Start Embedding Jetty server when WEB Application is started.
*
*/
public
void
contextInitialized
(
ServletContextEvent
event
)
{
try
{
// 1) Create a Jetty server with the 8081 port.
InetAddress
addr
=
InetAddress
.
getLocalHost
();