import socket
import hashlib
import socket
import base64
from threading import Thread
import time
#The websocket thread
class WebSocketStart(Thread):
def __init__(self,connect):
Thread.__init__(self)
self.connect = connect
self.isHandleShake = False
# the thread method
def run(self):
while True:
if not self.isHandleShake:
# 第一次连接,需要握手
header=self.getHeader()
secKey=header['Sec-WebSocket-Key']
acceptKey=self.generateAcceptKey(secKey)
response="HTTP/1.1 101 Switching Protocols\r\n"
response+="Upgrade: websocket\r\n"
response+="Connection: Upgrade\r\n"
response+="Sec-WebSocket-Accept: %s\r\n\r\n"%(acceptKey.decode('utf-8'))
self.connect.send(response.encode())
self.isHandleShake=True
print("HandleShake with client is Finish.")
else:
command = self.receiveMsg()
print(command)
self.sendMsgToClient("I have receive you msg")
# get the handleshake's header
def getHeader(self):
requestData = self.connect.recv(1024).decode()
requestList = requestData.split('\r\n')
headers={}
for reqItem in requestList:
if ': ' in reqItem:
unit = reqItem.split(': ')
headers[unit[0]]=unit[1]
return headers
# get the AcceptKey
def generateAcceptKey(self,secKey):
sha1 = hashlib.sha1()
sha1.update((secKey+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode())
sha1_result = sha1.digest()
acceptKey = base64.b64encode(sha1_result)
return acceptKey
# send message to client
def sendMsgToClient(self,msg):
import struct
sendMsg = struct.pack('!B',0x81)
length=len(msg)
if length <= 125:
sendMsg += struct.pack('!B', length)
elif length <= 65536:
sendMsg += struct.pack('!B', 126)
sendMsg += struct.pack('!H', length)
elif length == 127:
sendMsg += struct.pack('!B', 127)
sendMsg += struct.pack('!Q', length)
sendMsg += struct.pack('!%ds' % (length), msg.encode())
self.connect.send(sendMsg)
# receive msy from client
def receiveMsg(self):
info=self.connect.recv(8096)
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')
return body
def main():
socke = socket.socket()
socke.bind(('127.0.0.1',8908))
socke.listen(5)
while True:
try:
connect,address = socke.accept()
WebSocketStart(connect).start()
except:
time.sleep(1)
if __name__ == '__main__':
main()
python 原生实现websocket
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 说明 本例中对用户请求的响应均通过此类实现,此类为threading.Thread的子类,我们重写了run方法,当...
- 说明 在实例化一个WebSocketServer对象后,调用对象的begin方法,将启用WebSocket服务端程...
- 说明 此函数需要着重关注这个地方: nv是解除掩码后的数据,通过nv.encode()的方式编码后计算编码后的by...
- 说明 data_length = len(msg.encode()) 着重注意以上代码,因为msg为字符串,考虑到...
- WebSocket 传输内容支持文本或二进制数据,这些数据的边界靠帧(frame)来维护,其中帧的第二个字节低7位...