HTML5 WebSocket
菜鸟教程
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>websocket通信dome</title>
<style>
.main{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: cornsilk;
padding: 30px;
padding: 30px;
}
.top{
width: 400px;
padding: 30px;
background-color: burlywood;
}
.bottom{
width: 400px;
background-color: cadetblue;
padding: 30px;
}
</style>
</head>
<body>
<div class="main">
<div class="top">
<div style="padding-bottom: 20px;">
<span>输入内容:</span>
<input type="text" id="sendText">
</div>
<div>
<button id="send">发送</button>
 
 
 
<button id="reset">重置</button>
</div>
</div>
<div class="bottom">
<textarea name="" id="text" cols="50" rows="30"></textarea>
</div>
</div>
</body>
<script>
var ws = null;
var url = "ws://127.0.0.1:9999";
var send = document.getElementById('send');
var reset = document.getElementById('reset');
var textaa = document.getElementById('text');
var sendText = document.getElementById('sendText');
function open(){
if("WebSocket" in window){
if(ws){
ws.close();
ws = null;
}
ws = new WebSocket(url);
ws.onopen = function(evt){
sendMain();
};
ws.onmessage = function (evt){
console.log('信息--',evt)
textaa.value = textaa.value+"\n "+evt.data;
send.disabled = false;
ws.close();
ws = null;
}
}else{
textaa.value = textaa.value+"\n 您的浏览器不支持WebSocket";
}
}
function sendMain(){
send.disabled = true;
ws.send(sendText.value);
}
function resetMain(){
if(ws){
ws.close();
ws = null;
}
textaa.value = textaa.value + "\n 重置链接成功";
send.disabled = false;
}
send.onclick = function () { open(); }
reset.onclick = function () { resetMain(); }
</script>
</html>

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
效果
