package server.ws;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocketendpoint")
public class WsServer {
@OnOpen
public void onOpen() {
System.out.println("Open Connection ...");
}
@OnClose
public void onClose() {
System.out.println("Close Connection ...");
}
@OnMessage
public String onMessage(String message) throws IOException {
Runtime rt = Runtime.getRuntime();
String command = message;
Process proc = rt.exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
String out = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
out = out + s;
}
System.out.println("Command from the client: " + message);
String echoMsg = "Output from the server : " + out;
return echoMsg;
}
@OnError
public void onError(Throwable e) {
e.printStackTrace();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
<form>
<input id="message" type="text"> <input
onclick="wsSendMessage();" value="Run" type="button"> <input
onclick="wsCloseConnection();" value="Disconnect" type="button">
</form>
<br>
<textarea id="echoText" rows="25" cols="80"></textarea>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8080/WebSocketServerExample/websocketendpoint");
var echoText = document.getElementById("echoText");
echoText.value = "";
var message = document.getElementById("message");
webSocket.onopen = function(message){ wsOpen(message);};
webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Command sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wserror(message){
echoText.value += "Error ... \n";
}
</script>
</body>
</html>
?
|