I recently downloaded Play Framework from GitHub and successfully compiled it. My goal now is to implement WebSockets using a JavaScript client along with a WebSocket controller similar to the one outlined in the Using WebSockets documentation. However, despite being able to establish a WebSocket connection, the controller does not receive any messages that I send to it. Additionally, I encountered an issue where I am unable to close the WebSocket using ws.close();
. Strangely enough, refreshing my webpage in the browser results in the WebSocket closing on the server side.
How can I effectively send and receive WebSocket messages using Play Framework?
Below is the code snippet of my Play Framework WebSocketController:
public class TestSocket extends WebSocketController {
public static void hello(String name) {
while(inbound.isOpen()) {
WebSocketEvent evt = await(inbound.nextEvent());
if(evt instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame)evt;
System.out.println("received: " + frame.getTextData());
if(!frame.isBinary()) {
if(frame.getTextData().equals("quit")) {
outbound.send("Bye!");
disconnect();
} else {
outbound.send("Echo: %s", frame.getTextData());
}
}
} else if(evt instanceof WebSocketClose) {
System.out.println("socket closed");
}
}
}
}
And here is a peek at my JavaScript client implementation:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>WebSocket test</title>
<style>
.message {background: lightgray;}
</style>
<script>
window.onload = function() {
document.getElementById('sendbutton')
.addEventListener('click', sendMessage, false);
document.getElementById('connectbutton')
.addEventListener('click', connect, false);
document.getElementById('disconnectbutton')
.addEventListener('click', disconnect, false);
}
function writeStatus(message) {
var html = document.createElement("div");
html.setAttribute('class', 'message');
html.innerHTML = message;
document.getElementById("status").appendChild(html);
}
function connect() {
ws = new WebSocket("ws://localhost:9000/ws?name=TestUser");
ws.onopen = function(evt) {
writeStatus("connected");
}
ws.onclose = function(evt) {
writeStatus("disconnected");
}
ws.onmessage = function(evt) {
writeStatus("response: " + evt.data);
}
ws.onerror = function(evt) {
writeStatus("error: " + evt.data);
}
}
function disconnect() {
ws.close();
}
function sendMessage() {
ws.send(document.getElementById('messagefield').value);
}
</script>
</head>
<body>
<h1>WebSocket test</h1>
<button id="connectbutton">Connect</button>
<button id="disconnectbutton">Disconnect</button><br>
<input type="text" id="messagefield"/><button id="sendbutton">Send</button>
<div id="status"></div>
</body>
</html>