用于测试websocket连接,可以向服务器发送消息并显示接受的消息
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页</title>
</head>
<body>
<script>
var webSocket=new WebSocket("ws://localhost:8080/MedicalGameServer/WebSocket");
var sendMsg=function(){
var inputElement=document.getElementById("msg");
webSocket.send(inputElement.value);
inputElement.value="";
}
var send=function(event){
if(event.keyCode==13){
sendMsg();
}
}
var closeWS=function(){
webSocket.close();
document.getElementById("show").innerHTML="";
document.getElementById("msg").value="";
}
webSocket.onopen=function(){
document.getElementById('msg').onkeydown=send;
document.getElementById("sendBn").onclick=sendMsg;
document.getElementById("closeBn").onclick=closeWS;
console.log("WebSocket 连接成功!!");
}
webSocket.onmessage=function(event){
var show=document.getElementById("show");
show.innerHTML+=event.data+"<br/>";
show.scrollTop=show.scrollHeight;
}
webSocket.onclose=function(){
document.getElementById("msg").onkeydown=null;
document.getElementById("sendBn").onclick=null;
document.getElementById("closeBn").onclick=null;
console.log("WebSocket 已经被关闭了!!");
}
</script>
<!--展示的div -->
<div style="width:600px;height:400px; overflow-y:auto;border:1px solid #333;" id="show">
</div>
<br/>
<!-- 填入内容的框 -->
<input type="text" size="80" id="msg" name="msg" placeholder="发送内容">
<!-- 发送按钮框 -->
<input type="button" value="发送" id="sendBn" name="sendBn">
<br/>
<br/>
<!-- 退出登录按钮框 -->
<input type="button" value="退出登录" id="closeBn" name="closeBn">
</body>
</html>
|