zoukankan      html  css  js  c++  java
  • 基于websocket实现的web聊天室

    # -*- coding:utf-8 -*-
    import socket
    import base64
    import hashlib
    
    
    def get_headers(data):
        """
        将请求头格式化成字典
        :param data:
        :return:
        """
        header_dict = {}
        data = str(data, encoding='utf-8')
    
        header, body = data.split('
    
    ', 1)
        header_list = header.split('
    ')
        for i in range(0, len(header_list)):
            if i == 0:
                if len(header_list[i].split(' ')) == 3:
                    header_dict['method'], header_dict['url'], header_dict['protocol'] = header_list[i].split(' ')
            else:
                k, v = header_list[i].split(':', 1)
                header_dict[k] = v.strip()
        return header_dict      #返回格式化后的字典
    
    
    def send_msg(conn, msg_bytes):
        """
        WebSocket服务端向客户端发送消息
        :param conn: 客户端连接到服务器端的socket对象,即: conn,address = socket.accept()
        :param msg_bytes: 向客户端发送的字节
        :return:做了一个125,126,127的处理,然后跟魔法字符串拼接之后返回
        """
        import struct
    
        token = b"x81"
        length = len(msg_bytes)
        if length < 126:
            token += struct.pack("B", length)
        elif length <= 0xFFFF:
            token += struct.pack("!BH", 126, length)
        else:
            token += struct.pack("!BQ", 127, length)
    
        msg = token + msg_bytes       #token+魔法字符串
        conn.send(msg)
        return True
    
    
    def run():
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('127.0.0.1', 8003))
        sock.listen(5)
    
        conn, address = sock.accept()
        data = conn.recv(1024)             #服务端接收的数据
        headers = get_headers(data)        #处理后的请求头信息
        response_tpl = "HTTP/1.1 101 Switching Protocols
    " 
                       "Upgrade:websocket
    " 
                       "Connection:Upgrade
    " 
                       "Sec-WebSocket-Accept:%s
    " 
                       "WebSocket-Location:ws://%s%s
    
    "
    
        value = headers['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'    #魔法字符串
        ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())               #两次加密
        response_str = response_tpl % (ac.decode('utf-8'), headers['Host'], headers['url'])
        conn.send(bytes(response_str, encoding='utf-8'))
    
        while True:
            try:
                info = conn.recv(8096)
            except Exception as e:
                info = None
            if not info:
                break
    
            """
            10010101
            01111111
            00010101
            """
            payload_len = info[1] & 127
            if payload_len == 126:
                extend_payload_len = info[2:4]
                mask = info[4:8]
                decoded = info[8:]
            elif payload_len == 127:
                extend_payload_len = info[2:10]
                mask = info[10:14]
                decoded = info[14:]
            else:
                extend_payload_len = None
                mask = info[2:6]
                decoded = info[6:]
    
            bytes_list = bytearray()
            for i in range(len(decoded)):
                chunk = decoded[i] ^ mask[i % 4]
                bytes_list.append(chunk)
            body = str(bytes_list, encoding='utf-8')
            print('原生消息', info)
            print('解密后',body)
            body ="服务端回复:"+body
            send_msg(conn, body.encode('utf-8'))
        sock.close()
    
    if __name__ == '__main__':
        run()
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>基于websocket实现的聊天室</title>
    </head>
    <body>
        <div>
            <input type="text" id="txt"/>
            <input type="button" id="btn" value="提交" onclick="sendMsg();"/>
            <input type="button" id="close" value="关闭连接" onclick="closeConn();"/>
        </div>
        <div id="content"></div>
    
    <script type="text/javascript">
        var socket = new WebSocket("ws://127.0.0.1:8003/chatsocket");
    
        socket.onopen = function () {
            /* 与服务器端连接成功后,自动执行 */
    
            var newTag = document.createElement('div');
            newTag.innerHTML = "【连接成功】";
            document.getElementById('content').appendChild(newTag);
        };
    
        socket.onmessage = function (event) {
            /* 服务器端向客户端发送数据时,自动执行 */
            var response = event.data;
            var newTag = document.createElement('div');
            newTag.innerHTML = response;
            document.getElementById('content').appendChild(newTag);
        };
    
        socket.onclose = function (event) {
            /* 服务器端主动断开连接时,自动执行 */
            var newTag = document.createElement('div');
            newTag.innerHTML = "【关闭连接】";
            document.getElementById('content').appendChild(newTag);
        };
    
        function sendMsg() {
            var txt = document.getElementById('txt');
            socket.send(txt.value);
            txt.value = "";
        }
        function closeConn() {
            socket.close();
            var newTag = document.createElement('div');
            newTag.innerHTML = "【关闭连接】";
            document.getElementById('content').appendChild(newTag);
        }
    
    </script>
    </body>
    </html>
  • 相关阅读:
    经典SQL问题: 行转列,列转行
    RocketMQ之三:RocketMQ集群环境搭建
    mysql函数之五:group_concat mysql 把结果集中的一列数据用指定分隔符转换成一行
    并发编程之五--ThreadLocal
    RocketMQ之三:nameserver源码解析
    Spring之3:BeanFactory、ApplicationContext、ApplicationContextAware区别
    spring中InitializingBean接口使用理解
    ES之四:Elasticsearch Mapping类型映射概述与元字段类型
    spring容器启动的三种方式
    java的reflection和introspector
  • 原文地址:https://www.cnblogs.com/52-qq/p/8530862.html
Copyright © 2011-2022 走看看