package server.ws;
import java.io.IOException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
public class ProgrammaticEchoServer extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
final Session mySession = session;
mySession.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String text) {
try {
mySession.getBasicRemote().sendText("I got this (" + text + ") so I am sending it back !");
} catch (IOException ioe) {
System.out.println(
"oh dear, something went wrong trying to send the message back: " + ioe.getMessage());
}
}
});
}
}
package server.ws;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.*;
public class ProgrammaticEchoServerAppConfig implements ServerApplicationConfig {
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
Set configs = new HashSet<ServerEndpointConfig>();
ServerEndpointConfig sec = ServerEndpointConfig.Builder
.create(ProgrammaticEchoServer.class, "/programmaticecho").build();
configs.add(sec);
return configs;
}
@Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
return scanned;
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Socket JavaScript Echo Client</title>
<script language="javascript" type="text/javascript">
var echo_websocket;
function init() {
output = document.getElementById("output");
}
function send_echo() {
var wsUri = "ws://localhost:8080/WebSocketServerExample/programmaticecho";
writeToScreen("Connecting to " + wsUri);
echo_websocket = new WebSocket(wsUri);
echo_websocket.onopen = function(evt) {
writeToScreen("Connected !");
doSend(textID.value);
};
echo_websocket.onmessage = function(evt) {
writeToScreen("Received message: " + evt.data);
echo_websocket.close();
};
echo_websocket.onerror = function(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
echo_websocket.close();
};
}
function doSend(message) {
echo_websocket.send(message);
writeToScreen("Sent message: " + message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
</head>
<body>
<h1>Echo Server</h1>
<div style="text-align: left;">
<form action="">
<input onclick="send_echo()" value="Press to send" type="button">
<input id="textID" name="message" value="Hello Web Sockets"
type="text"> <br>
</form>
</div>
<div id="output"></div>
</body>
</html>
|