<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<!-- 在文本框写入的内容会在下面的div中显示出来 -->
<h1>Echo Test</h1>
<input type="text" id="sendTxt">
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">
var websocket = new WebSocket("ws://echo.websocket.org/");
//连接建立时触发
websocket.onopen = function(){
console.log("websocket open");
document.getElementById("recv").innerHTML = "Connected";
}
//连接关闭时触发
websocket.inclose = function(){
console.log('websocket close');
}
//客户端接收服务端数据时触发
websocket.onmessage = function(e){
console.log(e.data);
document.getElementById("recv").innerHTML = e.data;// 把input 里的数据给下方div
}
document.getElementById("sendBtn").onclick = function(){
var txt = document.getElementById("sendTxt").value;// 获取input里的数据
websocket.send(txt);//使用连接发送数据,把input里的数据 给 下方的div
}
</script>
</body>
</html>
效果: