python模拟websocket

server端:

#-*- coding:utf8 -*-

import threading

import hashlib

import socket

import base64

class websocket_thread(threading.Thread):

    def __init__(self, connection):

        super(websocket_thread, self).__init__()

        self.connection = connection

    

    def run(self):

        print 'new websocket client joined!'

        reply = '我草拟妹,终于握手成功'

        length = len(reply)

        while True:

            data = self.connection.recv(1024)

            print parse_data(data)

            self.connection.send('%c%c%s' % (0x81, length, reply))

            

def parse_data(msg):

    v = ord(msg[1]) & 0x7f

    if v == 0x7e:

        p = 4

    elif v == 0x7f:

        p = 10

    else:

        p = 2

    mask = msg[p:p+4]

    data = msg[p+4:]

    

    return ''.join([chr(ord(v) ^ ord(mask[k%4])) for k, v in enumerate(data)])

    

def parse_headers(msg):

    headers = {}

    header, data = msg.split('\r\n\r\n', 1)

    for line in header.split('\r\n')[1:]:

        key, value = line.split(': ', 1)

        headers[key] = value

    headers['data'] = data

    return headers

def generate_token(msg):

    key = msg + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

    ser_key = hashlib.sha1(key).digest()

    return base64.b64encode(ser_key)

            

if __name__ == '__main__':

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('192.168.1.163', 8098))

    sock.listen(50)

    

    while True:

        connection, address = sock.accept()

        try:

            data = connection.recv(1024)

            headers = parse_headers(data)

            token = generate_token(headers['Sec-WebSocket-Key'])

            connection.send('\

HTTP/1.1 101 WebSocket Protocol Hybi-10\r\n\

Upgrade: WebSocket\r\n\

Connection: Upgrade\r\n\

Sec-WebSocket-Accept: %s\r\n\r\n' % token)

            thread = websocket_thread(connection)

            thread.start()

        except socket.timeout:

            print 'websocket connection timeout'


client端:

        this.ws = new WebSocket("ws://192.168.1.163:8097");

        console.log(this.ws.readyState)

        this.ws.onopen = function (event) {

            console.log(event.data);

        };

        this.ws.onmessage = function (event) {

            console.log("response text msg: " + event.data);

        };

        this.ws.onerror = function (event) {

           

            console.log("Send Text fired an error");

            

        };

        this.ws.onclose = function (event) {

            console.log("WebSocket instance closed.");

        };

        console.log(WebSocket.OPEN)

        // this.ws.send("Hello WebSocket, I'm a text message.")

        setTimeout(function () {

            if (self.ws.readyState === WebSocket.OPEN) {

                self.ws.send("Hello WebSocket, I'm a text message.");

                console.log(event);

            }

            else {

                console.log("WebSocket instance wasn't ready...");

                // self.ws.send("Hello WebSocket, I'm a text message.");

            }

        }, 3);


以上是 python模拟websocket 的全部内容, 来源链接: www.h5w3.com/116117.html

回到顶部