websocket的使用

什么是websocket

Websocket是应用层第七层上的一个应用层协议,WebSocket 的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话。

HTTP 有 1.1 和 1.0 之说,也就是所谓的 keep-alive ,把多个 HTTP 请求合并为一个,但是 Websocket 其实是一个新协议,跟 HTTP 协议基本没有关系,只是为了兼容现有浏览器,所以使用了 HTTP 。

客户端首先会向服务端发送一个 HTTP 请求,包含一个 Upgrade 请求头来告知服务端客户端想要建立一个 WebSocket 连接

WebSocket 的其他特点:

  • 建立在 TCP 协议之上,服务器端的实现比较容易。
  • 与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
  • 数据格式比较轻量,性能开销小,通信高效。
  • 可以发送文本,也可以发送二进制数据。
  • 没有同源限制,客户端可以与任意服务器通信。
  • 协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。
  • 简易聊天使用:

<!DOCTYPE html>
<html>
<head>
    <title>简易聊天Demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
    <link href="https://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        html, body {
            min-height: 100%;
        }

        body {
            margin: 0;
            padding: 0;
            width: 100%;
            font-family: "Microsoft Yahei", sans-serif, Arial;
        }

        .container {
            text-align: center;
        }

        .title {
            font-size: 16px;
            color: rgba(0, 0, 0, 0.3);
            position: fixed;
            line-height: 30px;
            height: 30px;
            left: 0px;
            right: 0px;
            background-color: white;
        }

        .content {
            background-color: #f1f1f1;
            border-top-left-radius: 6px;
            border-top-right-radius: 6px;
            margin-top: 30px;
        }

        .content .show-area {
            text-align: left;
            padding-top: 8px;
            padding-bottom: 168px;
        }

        .content .show-area .message {
            width: 70%;
            padding: 5px;
            word-wrap: break-word;
            word-break: normal;
        }

        .content .write-area {
            position: fixed;
            bottom: 0px;
            right: 0px;
            left: 0px;
            background-color: #f1f1f1;
            z-index: 10;
            width: 100%;
            height: 160px;
            border-top: 1px solid #d8d8d8;
        }

        .content .write-area .send {
            position: relative;
            top: -28px;
            height: 28px;
            border-top-left-radius: 55px;
            border-top-right-radius: 55px;
        }

        .content .write-area #name {
            position: relative;
            top: -20px;
            line-height: 28px;
            font-size: 13px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="title">简易聊天demo</div>
    <div class="content">
        <div class="show-area"></div>
        <div class="write-area">
            <div>
                <button class="btn btn-default send">发送</button>
            </div>
            <div><input name="name" id="name" type="text" placeholder="input your name"></div>
            <div>
                <textarea name="message" id="message" cols="38" rows="4" placeholder="input your message..."></textarea>
            </div>
        </div>
    </div>
</div>

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
    $(function () {
        // var wsurl = 'ws://127.0.0.1:3000';
        var websocket;
        var i = 0;
        if (window.WebSocket) {
          // 原生js就支持的  
          // WebSocket 建立链接后 就不会在断  相当于打电话 只要不挂断就一直可以通讯
          // 1 前端必须按照步骤写上链接WebSocket 2 后台也需要对应链接上WebSocket
          // 对应我们来说 有人封装了 一个 sockect.io 他就是封装 WebSocket
          // 1 new WebSocket
            websocket = new WebSocket('ws://127.0.0.1:3000');

            //2 连接建立 websocket.onopen
            websocket.onopen = function (evevt) {
                console.log("WebSocket 链接上了");
                $('.show-area').append('<p class="bg-info message"><i class="glyphicon glyphicon-info-sign"></i>Connected to WebSocket server!</p>');
            }
            //3 收到后台发来消息就会执行 websocket.onmessage 
            websocket.onmessage = function (event) {
              // 在这里就 解析判断 后台返回什么数据 对应操作
                var msg = JSON.parse(event.data); //解析收到的json消息数据

                var type = msg.type; // 消息类型
                var umsg = msg.message; //消息文本
                var uname = msg.name; //发送人
                i++;
                if (type == 'usermsg') {
                    $('.show-area').append('<p class="bg-success message"><i class="glyphicon glyphicon-user"></i><a name="' + i + '"></a><span class="label label-primary">' + uname + ' : </span>' + umsg + '</p>');
                }
                if (type == 'system') {
                    $('.show-area').append('<p class="bg-warning message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>' + umsg + '</p>');
                }

                $('#message').val('');
                window.location.hash = '#' + i;
            }

            //发生错误 链接出错
            websocket.onerror = function (event) {
                i++;
                console.log("Connected to WebSocket server error");
                $('.show-area').append('<p class="bg-danger message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>Connect to WebSocket server error.</p>');
                window.location.hash = '#' + i;
            }

            //连接关闭 关闭链接
            websocket.onclose = function (event) {
                i++;
                console.log('websocket Connection Closed. ');
                $('.show-area').append('<p class="bg-warning message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>websocket Connection Closed.</p>');
                window.location.hash = '#' + i;
            }

            function send() {
                var name = $('#name').val();
                var message = $('#message').val();
                if (!name) {
                    alert('请输入用户名!');
                    return false;
                }
                if (!message) {
                    alert('发送消息不能为空!');
                    return false;
                }
                var msg = {
                    message: message,
                    name: name
                };
                try {
                    websocket.send(JSON.stringify(msg));
                } catch (ex) {
                    console.log(ex);
                }
            }

            //按下enter键发送消息
            $(window).keydown(function (event) {
                if (event.keyCode == 13) {
                    console.log('user enter');
                    send();
                }
            });

            //点发送按钮发送消息
            $('.send').bind('click', function () {
                send();
            });

        }
        else {
            alert('该浏览器不支持web socket');
        }

    });
</script>
</body>
</html>

WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它可以让客户端和服务器之间进行实时通信。在使用 WebSocket 时,客户端和服务器之间会建立一个长连接,这样客户端就可以向服务器发送数据,并从服务器接收数据。相比于传统的 HTTP 请求,WebSocket 的优势是可以实现实时通信,而且不需要频繁地发起请求和响应。 下面是使用 WebSocket 的基本步骤: 1. 客户端向服务器发起 WebSocket 连接请求。 2. 服务器接收到 WebSocket 连接请求,并建立连接。 3. 客户端和服务器之间进行实时通信。 4. 当通信结束时,客户端和服务器都可以关闭连接。 在 JavaScript 中,可以使用 WebSocket 对象来实现 WebSocket 通信。以下是一个简单的 WebSocket 示例: ```javascript // 创建 WebSocket 对象 var ws = new WebSocket('ws://localhost:8080'); // 监听连接事件 ws.onopen = function() { console.log('WebSocket 已连接'); }; // 监听消息事件 ws.onmessage = function(evt) { console.log('收到消息:' + evt.data); }; // 发送消息 ws.send('Hello, WebSocket!'); // 关闭连接 ws.close(); ``` 在上面的示例中,我们首先创建了一个 WebSocket 对象,然后监听了连接事件和消息事件。当连接建立成功时,会触发 onopen 事件;当收到消息时,会触发 onmessage 事件。我们还可以使用 send 方法向服务器发送消息,使用 close 方法关闭连接。 在服务器端,也可以使用 WebSocket 对象来实现 WebSocket 通信。具体实现方式可以参考各种编程语言的 WebSocket 库和示例代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值