websocket
java代码
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/echo")
public class EchoServer {
@OnMessage
public String echo(String incomingMessage){
return "I got this{"+incomingMessage+"}"
+"so i am sending it back !";
}
}
html代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content_Type" content="text/html"
charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" type="text">
var echo_websocket;
function init(){
output = document.getElementById("output");
}
function send_echo(){
var wsUri = "ws://localhost:8080/echoserver/echo";
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.date);
echo_websocket.close();
};
echo_websocket.onerror = function (evt){
writeToScreen('<spen style = "color : red;">
ERROR:</span>' + evt.date);
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 onclick = "textID" name = "message" value = "Hello world" type = "text">
<br>
</form>
</div>
<div id="output"></div>
</body>
</html>
2个错误
第一个是直接报错
第二个是 send_echo 未定义