# 调用socket的send方法发送str信息给web端
def sendMessage(msg):
global connectionlist
send_msg = b"" #使用bytes格式,避免后面拼接的时候出现异常
send_msg += b"\x81"
back_str = []
back_str.append('\x81')
data_length = len(msg.encode())
if data_length <= 125:
send_msg += str.encode(chr(data_length))
elif data_length <= 65535:
send_msg += struct.pack('b', 126)
send_msg += struct.pack('>h', data_length)
elif data_length <= (2^64-1):
send_msg += struct.pack('b', 127)
send_msg += struct.pack('>q', data_length)
else:
print (u'太长了')
for connection in connectionlist.values():
if send_message != None and len(send_message) > 0:
connection.send(send_message)
说明
data_length = len(msg.encode())
着重注意以上代码,因为msg为字符串,考虑到字符串中可能存在中文,所以需要转为bytes信息后再计算长度。