用jquery做一个websocket客户端
先看效果图:
功能很简单,就是作为客户端连接websocket,并实现接受和发送消息。具体代码如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket测试</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
var showToast = function (msg,option) {
outTime = 3000;
if (option&&option.outTime) {
outTime = option.outTime;
}
if (!$(".showtoastresult").html()) {
html = "<div class='showtoastresult' style='min-width: 50px;width: auto;padding: 10px 20px;font-size: 14px;font-weight: bold;background: rgba(7, 17, 27, 0.66);border-radius: 6px;color: rgb(255, 255, 255);top: 50%;z-index: 1000001;transform: translate3d(-50%, -50%, 0px);position: fixed;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);'></div>";
$(document.body).append(html);
}
$(".showtoastresult").html(msg);
$(".showtoastresult").fadeIn("slow").fadeOut(3000);
return false;
}
</script>
<style>
.newmessage{
width:100%;
}
.bubble{
background-color:lightgreen
position: relative;
max-width: 240px;
word-wrap: break-word;
text-align: left;
margin-left: 16px;
margin-right: 16px;
border-radius: 9px;
}
.bubble:after{
position: absolute;
border: 4.8px solid transparent;
content: " ";
top: 20px;
}
</style>
</head>
<body>
<div style='width:1300px'>
<input type='text' value='ws://127.0.0.1:9090' class="form-control" style='width:390px;display:inline'id='wsaddr'/>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" onclick='addsocket();'>连接</button>
<button type="button" class="btn btn-default" onclick='closesocket();'>断开</button>
</div>
<div style='margin-top:10px;margin-button:10px'>
<pre>说明:本页面主要用于测试websocket功能是否完善,内外网皆可测。
</pre></div>
</div>
<div class="row" >
<div id="output" style="border:1px solid #ccc;height:365px;overflow: auto;margin-left:15px"></div>
<div class="col-lg-6">
<div class="input-group" style=''>
<input type="text"id='message' class="form-control" style='width:810px' placeholder='待发信息' onkeydown="en(event);">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="doSend();">发送</button>
</span>
</div>
</div>
</div>
</div>
<script language="javascript"type="text/javascript">
function formatDate(now) {
var year=now.getFullYear();
var month=now.getMonth()+1;
var date=now.getDate();
var hour=now.getHours();
var minute=now.getMinutes();
var second=now.getSeconds();
return year+"-"+(month=month<10?("0"+month):month)+"-"+(date=date<10?("0"+date):date)+" "+(hour=hour<10?("0"+hour):hour)+":"+(minute=minute<10?("0"+minute):minute)+":"+(second=second<10?("0"+second):second);
}
var output;
var websocket;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function addsocket() {
var wsaddr = $("#wsaddr").val();
if (wsaddr=='') {
alert("请填写websocket的地址");
return false;
}
StartWebSocket(wsaddr);
}
function closesocket() {
websocket.close();
}
function StartWebSocket(wsUri) {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) }; }
function onOpen(evt) {
writeToScreen("<span style='color:red'>连接成功,现在你可以发送信息啦!!!</span>");
}
function onClose(evt) {
writeToScreen("<span style='color:red'>websocket连接已断开!!!</span>");
websocket.close();
}
function onMessage(evt) {
writeToScreen('<span style="color:blue">服务端回应 '+formatDate(new Date())+'</span><br/><span class="bubble">'+ evt.data+'</span>');
}
function onError(evt) {
writeToScreen('<span style="color: red;">发生错误:</span> '+ evt.data);
}
function doSend() {
var message=$("#message").val();
if (message=='') {
alert("请先填写发送信息");
$("#message").focus();
return false;
}
if (typeof websocket==="undefined"){
alert("websocket还没有连接,或者连接失败,请检测");
return false;
}
if (websocket.readyState==3) {
alert("websocket已经关闭,请重新连接");
return false;
}
console.log(websocket);
$("#message").val('');
writeToScreen('<span style="color:green">你发送的信息 ('+formatDate(new Date())+'</span><br/>'+ message);
websocket.send(message);
}
function writeToScreen(message) {
var div = "<div class='newmessage'>"+message+"</div>";
var d = $("#output");
var d=d[0];
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
$("#output").append(div);
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
function en(event){
var evt=evt?evt:(window.event?window.event:null);
if (evt.keyCode==13){
doSend()
}
}
</script>
</body>
</html>