当前位置: 移动技术网 > IT编程>脚本编程>Python > Python通过websocket与js客户端通信示例分析

Python通过websocket与js客户端通信示例分析

2019年06月14日  | 移动技术网IT编程  | 我要评论

7个月宝宝腹泻怎么办,中国梦想秀20130429,宜昌个人二手房网

具体的 websocket 介绍可见  

这里,介绍如何使用 python 与前端 js 进行通信。

websocket 使用 http 协议完成握手之后,不通过 http 直接进行 websocket 通信。

于是,使用 websocket 大致两个步骤:使用 http 握手,通信。

js 处理 websocket 要使用 ws 模块; python 处理则使用 socket 模块建立 tcp 连接即可,比一般的 socket ,只多一个握手以及数据处理的步骤。

握手

过程

包格式

js 客户端先向服务器端 python 发送握手包,格式如下:

get /chat http/1.1
host: server.example.com
upgrade: websocket
connection: upgrade
sec-websocket-key: dghlihnhbxbszsbub25jzq==
origin: http://example.com
sec-websocket-protocol: chat, superchat
sec-websocket-version: 13

服务器回应包格式:

http/1.1 101 switching protocols
upgrade: websocket
connection: upgrade
sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo=
sec-websocket-protocol: chat

其中, sec-websocket-key 是随机的,服务器用这些数据构造一个 sha-1 信息摘要。

方法为: key+migic , sha-1  加密, base-64 加密,如下:

python 中的处理代码

magic_string = '258eafa5-e914-47da-95ca-c5ab0dc85b11'
res_key = base64.b64encode(hashlib.sha1(sec_key + magic_string).digest())

握手完整代码

js 端

js 中有处理 websocket 的类,初始化后自动发送握手包,如下:

var socket = new websocket('ws://localhost:3368');

python 端

python 用 socket 接受得到握手字符串,处理后发送

host = 'localhost'
port = 3368
magic_string = '258eafa5-e914-47da-95ca-c5ab0dc85b11'
handshake_string = "http/1.1 101 switching protocols\r\n" \
      "upgrade:websocket\r\n" \
      "connection: upgrade\r\n" \
      "sec-websocket-accept: {1}\r\n" \
      "websocket-location: ws://{2}/chat\r\n" \
      "websocket-protocol:chat\r\n\r\n"
 
def handshake(con):
#con为用socket,accept()得到的socket
#这里省略监听,accept的代码,具体可见blog:http://blog.csdn.net/ice110956/article/details/29830627
 headers = {}
 shake = con.recv(1024)
 
 if not len(shake):
  return false
 
 header, data = shake.split('\r\n\r\n', 1)
 for line in header.split('\r\n')[1:]:
  key, val = line.split(': ', 1)
  headers[key] = val
 
 if 'sec-websocket-key' not in headers:
  print ('this socket is not websocket, client close.')
  con.close()
  return false
 
 sec_key = headers['sec-websocket-key']
 res_key = base64.b64encode(hashlib.sha1(sec_key + magic_string).digest())
 
 str_handshake = handshake_string.replace('{1}', res_key).replace('{2}', host + ':' + str(port))
 print str_handshake
 con.send(str_handshake)
return true

通信

不同版本的浏览器定义的数据帧格式不同, python 发送和接收时都要处理得到符合格式的数据包,才能通信。

python 接收

python 接收到浏览器发来的数据,要解析后才能得到其中的有用数据。

浏览器包格式

固定字节:

( 1000 0001 或是 1000 0002 )这里没用,忽略

包长度字节:

第一位肯定是 1 ,忽略。剩下 7 个位可以得到一个整数 (0 ~ 127) ,其中

( 1-125 )表此字节为长度字节,大小即为长度;

(126)表接下来的两个字节才是长度;

(127)表接下来的八个字节才是长度;

用这种变长的方式表示数据长度,节省数据位。

mark 掩码:

mark 掩码为包长之后的 4 个字节,之后的兄弟数据要与 mark 掩码做运算才能得到真实的数据。

兄弟数据:

得到真实数据的方法:将兄弟数据的每一位 x ,和掩码的第 i%4 位做 xor 运算,其中 i 是 x 在兄弟数据中的索引。

完整代码

def recv_data(self, num):
 try:
  all_data = self.con.recv(num)
  if not len(all_data):
   return false
 except:
  return false
 else:
  code_len = ord(all_data[1]) & 127
  if code_len == 126:
   masks = all_data[4:8]
   data = all_data[8:]
  elif code_len == 127:
   masks = all_data[10:14]
   data = all_data[14:]
  else:
   masks = all_data[2:6]
   data = all_data[6:]
  raw_str = ""
  i = 0
  for d in data:
   raw_str += chr(ord(d) ^ ord(masks[i % 4]))
   i += 1
  return raw_str

js 端的 ws 对象,通过 ws.send(str) 即可发送

ws.send(str)

python 发送

python 要包数据发送,也需要处理,发送包格式如下

固定字节:固定的 1000 0001( ‘ \x81 ′ )

包长:根据发送数据长度是否超过 125 , 0xffff(65535) 来生成 1 个或 3 个或 9 个字节,来代表数据长度。

def send_data(self, data):
 if data:
  data = str(data)
 else:
  return false
 token = "\x81"
 length = len(data)
 if length < 126:
  token += struct.pack("b", length)
 elif length <= 0xffff:
  token += struct.pack("!bh", 126, length)
 else:
  token += struct.pack("!bq", 127, length)
 #struct为python中处理二进制数的模块,二进制流为c,或网络流的形式。
 data = '%s%s' % (token, data)
 self.con.send(data)
 return true

js 端通过回调函数 ws.onmessage() 接受数据

ws.onmessage = function(result,ntime){
alert("从服务端收到的数据:");
alert("最近一次发送数据到现在接收一共使用时间:" + ntime);
console.log(result);
}

最终代码

python服务端

# _*_ coding:utf-8 _*_
__author__ = 'patrick'

import socket
import threading
import sys
import os
import mysqldb
import base64
import hashlib
import struct
 
# ====== config ======
host = 'localhost'
port = 3368
magic_string = '258eafa5-e914-47da-95ca-c5ab0dc85b11'
handshake_string = "http/1.1 101 switching protocols\r\n" \
      "upgrade:websocket\r\n" \
      "connection: upgrade\r\n" \
      "sec-websocket-accept: {1}\r\n" \
      "websocket-location: ws://{2}/chat\r\n" \
      "websocket-protocol:chat\r\n\r\n"
 
class th(threading.thread):
 def __init__(self, connection,):
  threading.thread.__init__(self)
  self.con = connection
 
 def run(self):
  while true:
   try:
     pass
  self.con.close()
 
 def recv_data(self, num):
  try:
   all_data = self.con.recv(num)
   if not len(all_data):
    return false
  except:
   return false
  else:
   code_len = ord(all_data[1]) & 127
   if code_len == 126:
    masks = all_data[4:8]
    data = all_data[8:]
   elif code_len == 127:
    masks = all_data[10:14]
    data = all_data[14:]
   else:
    masks = all_data[2:6]
    data = all_data[6:]
   raw_str = ""
   i = 0
   for d in data:
    raw_str += chr(ord(d) ^ ord(masks[i % 4]))
    i += 1
   return raw_str
 
 # send data
 def send_data(self, data):
  if data:
   data = str(data)
  else:
   return false
  token = "\x81"
  length = len(data)
  if length < 126:
   token += struct.pack("b", length)
  elif length <= 0xffff:
   token += struct.pack("!bh", 126, length)
  else:
   token += struct.pack("!bq", 127, length)
  #struct为python中处理二进制数的模块,二进制流为c,或网络流的形式。
  data = '%s%s' % (token, data)
  self.con.send(data)
  return true
 
 
 # handshake
 def handshake(con):
  headers = {}
  shake = con.recv(1024)
 
  if not len(shake):
   return false
 
  header, data = shake.split('\r\n\r\n', 1)
  for line in header.split('\r\n')[1:]:
   key, val = line.split(': ', 1)
   headers[key] = val
 
  if 'sec-websocket-key' not in headers:
   print ('this socket is not websocket, client close.')
   con.close()
   return false
 
  sec_key = headers['sec-websocket-key']
  res_key = base64.b64encode(hashlib.sha1(sec_key + magic_string).digest())
 
  str_handshake = handshake_string.replace('{1}', res_key).replace('{2}', host + ':' + str(port))
  print str_handshake
  con.send(str_handshake)
  return true
 
def new_service():
 """start a service socket and listen
 when coms a connection, start a new thread to handle it"""
 
 sock = socket.socket(socket.af_inet, socket.sock_stream)
 try:
  sock.bind(('localhost', 3368))
  sock.listen(1000)
  #链接队列大小
  print "bind 3368,ready to use"
 except:
  print("server is already running,quit")
  sys.exit()
 
 while true:
  connection, address = sock.accept()
  #返回元组(socket,add),accept调用时会进入waite状态
  print "got connection from ", address
  if handshake(connection):
   print "handshake success"
   try:
    t = th(connection, layout)
    t.start()
    print 'new thread for client ...'
   except:
    print 'start new thread error'
    connection.close()
 
 
if __name__ == '__main__':
 new_service()

js客户 端

<script>
var socket = new websocket('ws://localhost:3368');
ws.onmessage = function(result,ntime){
alert("从服务端收到的数据:");
alert("最近一次发送数据到现在接收一共使用时间:" + ntime);
console.log(result);
}
</script>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网