使用websocket做一个及时通讯功能————03使用网页完成即时通讯群聊天

接着上讲,这次我将会完成界面在线聊天的功能

1.打开上次的项目

在resource下建立以下几个文件和文件夹:如图
使用websocket做一个及时通讯功能————03使用网页完成即时通讯群聊天_第1张图片
1.jq下载地址:点击下载

2.hsocket.js

//是否支持websocket
function isSupportWebSokent() {
    var result=false
    if ('WebSocket' in window) result=true
    if ('MozWebSocket' in window) result=true
    return result
}
//初始化websocket并接收链接消息
function Hsocket(url,from,to) {
    this.websocket="";
    this.from=from.toString();
    this.to=-1;
    if(to!=null) this.to=to;
    this.to=this.to.toString()
    if ('WebSocket' in window) {
        this.websocket = new WebSocket(url);
    } else if ('MozWebSocket' in window) {
        this.websocket = new MozWebSocket(url);
    }
    var data=""
    this.websocket.onopen=function (event) {
        data=event.data;
    }
    return data
}
//发送消息
Hsocket.prototype.sendMessage=function (message) {
    var from=this.from;
    var to=this.to;
    var params={from:from, to:to, msg:message}
    this.websocket.send(JSON.stringify(params))
}
//主动关闭链接
Hsocket.prototype.close=function () {
    this.websocket.close()
}

解释一波吧,isSupportWebSokent方法为用来判断是否支持websocket协议,Hsocket对象初略封装了websocket
其他的自己看注释 不想说了
3.登录界面index.html

<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>聊天登录界面title>
    <style>
        input {
            -webkit-user-select: auto;
        }
        h3{text-align: center;margin-top: 50px;}
    style>
head>

<body>
<header class="mui-bar mui-bar-nav">
    <h4 class="mui-title" style="text-align: center">登录h4>
header>
<div class="mui-content">
    <h5 style="text-align: center">欢迎登录h5>
    请输入id: <input id="username" style="width: 50%;" type="text" onkeyup="value=value.replace(/[^\d]/g,'')" />
    <div style="margin: 20px 35%;"><button id="loginBtn">登录button>div>
div>
<script src="js/jquery.min.js">script>
<script>
    document.getElementById("loginBtn").addEventListener("click",function(){
        var id=document.getElementById("username").value
        if(id==""){
            alert("请输入id")
        }else if(parseInt(id)>8){
            alert("id为1-8")
        }else{
            $.post("http://localhost:8080/login",{id:id},function (data) {
                if(data.code==200){
                    window.location.href="views/all-chat.html?id="+id+"&header="+data.msg
                }else{
                    alert(data.msg)
                }
            })
        }
    })
script>
body>

html>

3.群聊界面all-chat.html


<html>

<head>
    <meta charset="UTF-8">
    <title>title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <style>
        textarea {
            -webkit-user-select: auto;
            padding: 8px 5px!important;
            width: 77%!important;
            margin-left: 1%;
            margin-right: 1%;
            margin-bottom: 5px!important;
            min-height: 22px;
            overflow: scroll;
            overflow-y: hidden;
            overflow-x: hidden;
            position: absolute;
        }

        #sendBtn {
            padding: 9px!important;
            width: calc(20% - 8px);
            position: absolute;
            bottom: 6px;
            margin-left: 5px;
            right: 0;
        }

        .bottom {
            position: relative;
            /*bottom: 0;*/
            width: 100%;
            padding-top: 10px;
            height: 45px;
        }

        .bubbleItem {
            width: 100%;
        }

        .bubble {
            position: relative;
            line-height: 30px;
            padding: 3px 10px;
            border-radius: 7px;
            margin-top: 15px;
            display: inline-block;
            background-color: white;
            max-width: calc(100% - 100px);
        }

        .leftBubble {
            position: relative;
            margin-left: 20px;
            border: 1px solid #00b6b6;
            background-color: #f8fdfc;
        }

        .leftBubble .bottomLevel {
            position: absolute;
            top: 10px;
            left: -10px;
            border-top: 10px solid #00b6b6;
            border-left: 10px solid transparent;
        }

        .leftBubble .topLevel {
            position: absolute;
            top: 11px;
            left: -8px;
            border-top: 10px solid #f8fdfc;
            border-left: 10px solid transparent;
            z-index: 100;
        }

        .rightBubble {
            position: relative;
            margin-right: 20px;
            float: right;
            border: 1px solid #aaa;
        }

        .rightBubble .bottomLevel {
            position: absolute;
            top: 10px;
            right: -10px;
            border-top: 10px solid #aaa;
            border-right: 10px solid transparent;
        }

        .rightBubble .topLevel {
            position: absolute;
            top: 11px;
            right: -8px;
            border-top: 10px solid #fff;
            border-right: 10px solid transparent;
            z-index: 100;
        }

        .clearfix:after {
            visibility: hidden;
            display: block;
            font-size: 0;
            content: " ";
            clear: both;
            height: 0;
        }

        .img-fit {
            width: 38px;
            height: 38px;
            object-fit: cover;
            margin-top: 10px;
            border-radius: 50%;
        }

        .f-r {
            float: right;
        }

        .f-l {
            float: left;
        }

        .hBorder {
            font-family: Arial, Helvetica, sans-serif;
        }
        #show{
            height:0px;overflow:hidden
        }
        #allContent{
            overflow: auto;
        }
        #content{
            padding: 5px;
        }
    style>
head>

<body>
<div class="mui-content">
    <div id="allContent">
        <div id="content">div><div id="show">div>
    div>
    <div class="bottom" id="bottom">
        <textarea id="area" rows="1" cols="10">textarea>
        <button id="sendBtn">发送button>
    div>
div>
<script type="text/javascript" src="../../js/hsocket.js">script>
<script type="text/javascript">
    document.getElementById("allContent").style.height=(window.innerHeight - 60)+"px"
    if(isSupportWebSokent()) {
        var ws = new Hsocket('ws://localhost:8080/webSocket/' + GetQueryString("id"), GetQueryString("id"))
        document.getElementById("sendBtn").addEventListener("click", function() {
            var area = document.getElementById("area").value
            if(area != "") {
                createSelfText(GetQueryString("header"),area)
                var message={"sender": GetQueryString("header"),"type":"text","content":area}
                ws.sendMessage(JSON.stringify(message))
            }
        })
        ws.websocket.onmessage = function(event) {
            var message=JSON.parse(event.data)
            createOtherText(message.sender,message.content);
        }
    }

    function createOtherText(header,area) {
        var div = document.createElement("div")
        div.classList = "bubbleItem"

        var imgDiv = document.createElement("div")
        imgDiv.classList = "f-l"
        var img = document.createElement("img")
        img.classList = "img-fit"
        img.src = header
        imgDiv.appendChild(img)
        div.appendChild(imgDiv)

        var textD = document.createElement("div")
        textD.classList = "bubble leftBubble"
        var textS = document.createElement("span")
        textS.innerText = area
        textD.appendChild(textS)
        var textS1 = document.createElement("span")
        textS1.classList = "bottomLevel"
        textD.appendChild(textS1)
        var textS2 = document.createElement("span")
        textS2.classList = "topLevel"
        textD.appendChild(textS2)
        div.appendChild(textD)

        document.getElementById("content").appendChild(div)
        document.getElementById("show").scrollIntoView();
        document.getElementById("area").value = ""
    }

    function createSelfText(header,area) {
        var div = document.createElement("div")
        div.classList = "bubbleItem clearfix"

        var spanB = document.createElement("span")
        spanB.classList = "hBorder"
        div.appendChild(spanB)

        var imgDiv = document.createElement("div")
        imgDiv.classList = "f-r"
        var img = document.createElement("img")
        img.classList = "img-fit"
        img.src = header
        imgDiv.appendChild(img)
        div.appendChild(imgDiv)

        var textD = document.createElement("div")
        textD.classList = "bubble rightBubble"
        var textS = document.createElement("span")
        textS.innerText = area
        textD.appendChild(textS)
        var textS1 = document.createElement("span")
        textS1.classList = "bottomLevel"
        textD.appendChild(textS1)
        var textS2 = document.createElement("span")
        textS2.classList = "topLevel"
        textD.appendChild(textS2)
        div.appendChild(textD)

        document.getElementById("content").appendChild(div)
        document.getElementById("show").scrollIntoView();
        document.getElementById("area").value = ""

    }
    function GetQueryString(name) {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    }
script>
body>

html>

好了,大工完成。现在你可以登录到群聊聊天室里进行聊天了

你可能感兴趣的:(websoket实战,webSocket实战)