注意:需要先安装配置Node.js,再通过NPM命令安装ws模块(npm install -g ws)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="">
<script src=""></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<style>
.div_1{width:400px; height:300px; background-color:#CCC; padding-top:10px;}
.div_1 #content{width:380px; height:250px; background-color:#FFF; margin-left:10px; overflow:auto;}
#message{width:300px; height:20px; margin-top:10px; margin-left:10px;}
#button_1{width:65px; height:24px; border:0px; background-color:#FFF; color:#00F; cursor:pointer;}
</style>
</head>
<body>
<div class="div_1">
<div id="content"></div><!--content-->
<form action="" method="post" id="form_1">
<input id="message" type="text" />
<input id="button_1" type="submit" value="Send" />
</form>
</div><!--div_1-->
<script>
var setupChat = function(){
var webSocket = new WebSocket('ws://localhost:8888/'); //参数为WebSocket服务器的实际IP地址
webSocket.onopen = function(event){ //当与服务器的连接建立时触发
$('#content').append("<br>连接到服务器");
};
webSocket.onmessage = function(event){ //当与服务器的连接发送一条消息时触发
$('#content').append("<br>" + event.data);
$('#content').animate({scrollTop:$('#content').height()});
};
webSocket.onclose = function(event){ //当与服务器的连接丢失或关闭时触发
$('#content').append("<br>断开连接");
};
$('form#form_1').submit(function(e){
e.preventDefault();
var textfield = $('#message');
webSocket.send(textfield.val());
textfield.val("");
});
};
setupChat();
</script>
</body>
</html>