用python实现的websocket代码Word文件下载.docx
《用python实现的websocket代码Word文件下载.docx》由会员分享,可在线阅读,更多相关《用python实现的websocket代码Word文件下载.docx(15页珍藏版)》请在冰点文库上搜索。
xA:
pongframe
xB-xF:
controlreservedframes
Mask(bit8):
thisbitdetermineswhetherthisspecificframeusesamaskornot.
PayloadLength(bits9-15,or16-31,or16-79):
thesesevenbytesdeterminethepayloadlength.Ifthelengthis126,thelengthisactuallydeterminedbybits16through31(thatis,thefollowingtwobytes).Ifthelengthis127,thelengthisactuallydeterminedbybits16through79(thatis,thefollowingeightbytes).
MaskingKey(thefollowingfourbytes):
thisrepresentsthemask,iftheMaskbitissetto1.
PayloadData(thefollowingdata):
finally,thedata.Thepayloaddatamaybesentovermultipleframes;
weknowthesizeoftheentiremessagebythepayloadlengththatwassent,andcanappenddatatogethertoformasinglemessageuntilwereceivethemessagewiththeFinflag.Eachconsecutivepayload,ifitexists,willcontainthe0“continuationframe”opcode.
服务端代码:
#coding=utf8
#!
/usr/bin/python
import
struct,socket
hashlib
threading,random
time
struct
from
base64
b64encode,
b64decode
connectionlist
=
{}
g_code_length
0
g_header_length
def
hex2dec(string_num):
return
str(int(),
16))
get_datalength(msg):
global
print
(len(msg))
ord(msg[1])
&
127
received_length
0;
if
==
126:
#g_code_length
msg[2:
4]
(ord(msg[2])<
<
8)
+
(ord(msg[3]))
('
>
H'
str(msg[2:
4]))[0]
8
elif
127:
10]
Q'
10]))[0]
14
else:
6
int(g_code_length)
parse_data(msg):
masks
msg[4:
8]
data
msg[8:
]
msg[10:
14]
msg[14:
6]
msg[6:
i
raw_str
'
for
d
in
data:
+=
chr(ord(d)
^
ord(masks[i%4]))
1
(u"
总长度是:
%d"
%
int(g_code_length))
sendMessage(message):
message_utf_8
utf-8'
)
connection
():
back_str
[]
\x81'
data_length
len(message_utf_8)
125:
(chr(data_length))
65535
:
b'
126))
h'
data_length))
#(chr(data_length
8))
0xFF))
#a
data_length)
#b
chr(data_length
#c
0xFF)
(2^64-1):
#(chr(127))
127))
q'
else
(u'
太长了'
msg
c
back_str:
c;
str(msg)
message_utf_8#.encode('
#(str(u"
\x00%s\xFF\n\n"
message)))
#这个是旧版
#print
send
message:
message)
!
None
and
len(back_str)
0:
(back_str)
deleteconnection(item):
del
connectionlist['
connection'
+item]
class
WebSocket:
#继承Thread
GUID
"
258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
__init__(self,conn,index,name,remote,
path="
/"
):
初始化父类Thread
conn
index
name
remote
path
run(self):
#重载Thread的run
print('
Socket%s
Start!
headers
False
while
True:
False:
Start
Handshaken
with
%s!
)
\r\n\r\n'
-1:
header,
1)
line
("
\r\n"
)[1:
]:
key,
value
headers[key]
headers["
Location"
%(headers["
Host"
],
key
headers['
Sec-WebSocket-Key'
token
b64encode(str(key
)).digest())
handshake="
HTTP/
101
Switching
Protocols\r\n"
\
Upgrade:
websocket\r\n"
Connection:
Upgrade\r\n"
Sec-WebSocket-Accept:
+(token)+"
WebSocket-Origin:
+str(headers["
Origin"
])+"
WebSocket-Location:
\r\n\r\n"
True
Socket
%s
success!
%,
sendMessage(u'
Welcome,
mm=
len(mm)
continue
get_datalength(mm)
#接受的长度
mm
-
parse_data
#utf8
msg_unicode
str.decode('
ignore'
#unicode
msg_unicode=='
quit'
Logout!
nowTime
%H:
%M:
%S'
()))
say:
%s'
(nowTime,
+'
Logout'
))
deleteconnection(str)
break
#退出线程
Got
msg:
msg_unicode,
msg_unicode))
#重置buffer和bufferlength
WebSocketServer(object):
__init__(self):
begin(self):
print(
WebSocketServer
12345))
i=0
connection,
address
username=address[0]
newSocket
WebSocket(connection,i,username,address)
()
#开始线程,执行run函数
+str(i)]=connection
__name__
__main__"
server
WebSocketServer()
客户端代码:
DOCTYPE
html>
1.<
head>
title>
WebSocket<
/title>
style>
html,
body
{
font:
normal
arial,
helvetica;
}
#log
width:
440px;
height:
200px;
border:
1px
solid
#7F9DB9;
overflow:
auto;
#msg
330px;
/style>
script>
var
socket;
function
init()
host
;
try
socket
new
WebSocket(host);
(msg)
log('
Connected'
);