index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Tomcat WebSocket Chat</title>
<script>
//设定WebSocket,注意协议是ws,请求是指向对应的WebSocketServlet的
/*设定WebSocket,注意协议是ws,请求是指向对应的WebSocketServlet的
var url = "ws://127.0.0.1:8080/j2ee6/echo.ws";
// 创建WebSocket实例,,下面那个MozWebSocket是Firefox的实现
if (‘WebSocket’ in window) {
ws = new WebSocket(url);
} else if (‘MozWebSocket’ in window) {
ws = new MozWebSocket(url);
} else {
alert(‘Unsupported.’);
return;
}*/
var ws = new WebSocket("ws://218.196.14.208:8080/webSocket/webServlet");
//WebSocket握手完成,连接成功的回调
//有个疑问,按理说new WebSocket的时候就会开始连接了,如果在设置onopen以前连接成功,是否还会触发这个回调
ws.onopen = function() {
//请求成功
};
//收到服务器发送的文本消息, event.data表示文本内容
ws.onmessage = function(message) {
document.getElementById("talkInfo").innerHTML+=message.data+"<hr/>";
};
//关闭WebSocket的回调
ws.onclose = function() {
//alert(‘Closed!’);
};
// 通过WebSocket想向服务器发送一个文本信息
function postToServer() {
ws.send(document.getElementById("content").value);
document.getElementById("content").value = "";
}
//关闭WebSocket
function closeConnect() {
ws.close();
}
</script>
<style>
* {
margin: 0 auto;
padding: 0px;
font-size: 12px;
font-family: "微软雅黑";
line-height: 26px;
}
#bigbox {
margin:0px auto;
padding:0px;
width:70%;
}
#talkInfo{
width:100%;
height:500px;
border:1px solid red;
overflow: scorll;
}
#operation{
width:100%;
height:30px;
margin-top:10px;
}
#content{
height:30px;
line-height:30px;
}
</style>
</head>
<body>
<div id="bigbox">
<div id="talkInfo"></div>
<div id="operation">
<center>
<input type="text" name="content" id="content" size="100"/>
<input type="button" value=" 发送 " onclick="postToServer()" />
<input type="button" value=" 我闪 " onclick="closeConnect()" />
</center>
</div>
</div>
</body>
</html>
以一种进取的和明智的方式同它们奋斗。