websocket服务器(python版) 下载本文

内容发布更新时间 : 2024/12/26 2:17:38星期一 下面是文章的全部内容请认真阅读。

websocket服务器(python版)

服务器

#coding=utf8 #!/usr/bin/python

import struct,socket import hashlib

import threading,random import time import struct

from base64 import b64encode, b64decode

connectionlist = {} g_code_length = 0 g_header_length = 0

def hex2dec(string_num):

return str(int(string_num.upper(), 16))

def get_datalength(msg): global g_code_length global g_header_length

print (len(msg))

g_code_length = ord(msg[1]) & 127 received_length = 0; if g_code_length == 126: #g_code_length = msg[2:4]

#g_code_length = (ord(msg[2])<<8) + (ord(msg[3])) g_code_length = struct.unpack('>H', str(msg[2:4]))[0] g_header_length = 8 elif g_code_length == 127: #g_code_length = msg[2:10]

g_code_length = struct.unpack('>Q', str(msg[2:10]))[0] g_header_length = 14 else:

g_header_length = 6

g_code_length = int(g_code_length) return g_code_length

def parse_data(msg): global g_code_length

g_code_length = ord(msg[1]) & 127 received_length = 0; if g_code_length == 126:

g_code_length = struct.unpack('>H', str(msg[2:4]))[0] masks = msg[4:8] data = msg[8:]

elif g_code_length == 127:

g_code_length = struct.unpack('>Q', str(msg[2:10]))[0] masks = msg[10:14] data = msg[14:] else:

masks = msg[2:6] data = msg[6:] i = 0 raw_str = ''

for d in data:

raw_str += chr(ord(d) ^ ord(masks[i%4])) i += 1

print (u\总长度是:%d\ return raw_str

def sendMessage(message): global connectionlist

message_utf_8 = message.encode('utf-8') for connection in connectionlist.values(): back_str = []

back_str.append('\\x81')

data_length = len(message_utf_8)