websocket协议实现验证码
常见的验证码功能走的都是http协议,点击一下验证码图片里,图片的src指向一个server端地址,而server端返回的数据为二进制图片文件,这样,验证码图片便生成了并点击一下变化一下了。
websocket协议不太一样,它的返回值并不支持二进制文件,只能传输字符串。但前端其实支持dataUrl,格式类似于<img src="data:image/gif;base64,xxxxxxxxxxxxxxx"> xxxxx为base64位的字符串。所以,可以换个思路在ws协议下也实现验证码功能——在server端将二进制文件编码为base64位的字符串,返回给客户端,客户端将字符串填进img的src属性里,即可实现验证码功能。
python版server端代码大概如下:
=============================================================================
#coding=utf-8
import Image,ImageDraw,ImageFont,cStringIO,base64,random
'''验证码管理器'''
__CODE_COUNT = 4
def createVerificationCode():
allCode = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
code = ""
for i in xrange(__CODE_COUNT):
code += random.choice(allCode)
return code
def getImageBase64Data(code):
text = code
im = Image.new("RGB",(70,25),(0,0,0))
dw = ImageDraw.Draw(im)
dw.text((5,0),text,fill="green",font=ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansOblique.ttf',20))
buf = cStringIO.StringIO()
im.save(buf,"gif")
return base64.b64encode(buf.getvalue())
if __name__ == "__main__" verificationCode = createVerificationCode() imageBase64Data = getImageBase64Data(verificationCode) socket.send(imageBase64Data)
===================================================================
客户端如下:
img.src = "data:image/gif;base64,"+ data.imageBase64Data;
====================================================================