canyin-project/ybcy/chat.html

139 lines
2.8 KiB
HTML
Raw Normal View History

2024-11-01 16:07:54 +08:00
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>聊天室</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<style>
.right {
color: blue;
display:block;
float:right;
width:100%;
}
</style>
<div style="width: 500px; margin:0 auto;">
<div class="log" id='scrolldIV' style="height:500px;border: 2px solid #ccc;line-height: 1.5em;overflow:auto" >
=======聊天室======
</div>
<!--<input type="button" value="连接" onClick="link()">-->
<input type="hidden" value="" id="fd">
<!--<input type="button" value="断开" onClick="dis()">-->
<div >
<input type="text" id="text">
<input type="button" value="发送" onClick="send()" id="submit">
</div>
</div>
<script>
$(document).keydown(function(event){
if(event.keyCode==13){
$("#submit").click();
}
});
$(function () {
//$("#text").focus();
link();
})
function link() {
if(window.WebSocket) {
var url = 'wss://v2.bkycms.com:9527';
socket = new WebSocket(url);
console.log(socket);
socket.onopen = function (evt) {
console.log("握手成功");
log1('<div>连接成功</div>')
}
socket.onmessage = function (msg) {
var data = $.parseJSON(msg.data)
if (data.msg.length <= 0) {
$("#fd").val(data.no);
} else {
log(data);
}
var div = document.getElementById('scrolldIV');
div.scrollTop = div.scrollHeight;
}
socket.onclose = function () {
log1('<div>断开连接</div>')
}
}else{
alert("您的浏览器不支持WebSocket");
}
}
function dis() {
socket.close();
socket = null;
}
function log1(data) {
$('.log').append(data);
}
function log(data) {
var nowFd = $("#fd").val();
console.log(data);
var role;
if(data['no'] == nowFd){
role ="我";
$('.log').append("<div class='right'>" + role+":"+ data['msg'] + '</div>');
} else {
$('.log').append("<div >" + data.role+": "+data['msg'] + '</div>');
}
}
function send() {
var text = $('#text').val();
if(text.length > 0){
socket.send(text);
$("#text").val('');
}
$("#text").focus();
}
function send2() {
var json = JSON.stringify({'type': 'php', 'msg': $('#text2').attr('value')})
socket.send(json);
}
</script>
</body>
</html>