python与html5搭建聊天室_基于Html5 websocket和Python的在线聊天室

该博客详细介绍了如何实现一个WebSocket服务器,包括连接管理、握手协议、消息发送和接收等功能。通过多线程处理客户端连接,确保了服务的并发性能。WebSocket协议的关键部分如Sec-WebSocket-Key的验证也得到了实现,使得服务器能够识别并建立安全的WebSocket连接。
摘要由CSDN通过智能技术生成

import socket

import struct

import hashlib

import threading,random

connectionlist = {}

def sendMessage(message):

global connectionlist

for connection in connectionlist.values():

connection.send("\x00%s\xFF" %message)

def deleteconnection(item):

global connectionlist

del connectionlist['connection'+item]

class WebSocket(threading.Thread):

def __init__(self, conn, index, name, remote, path="/"):

threading.Thread.__init__(self)

self.conn = conn

self.index = index

self.name = name

self.remote = remote

self.path = path

self.buffer = ""

def run(self):

print 'Socket %s Start!' %self.index

headers = {}

self.handshaken = False

while True:

if self.handshaken == False:

print 'Socket %s Start Handshaken with %s!' %(self.index, self.remote)

self.buffer += self.conn.recv(1024)

if self.buffer.find('\r\n\r\n') != -1:

header, data = self.buffer.split('\r\n\r\n', 1)

for line in header.split("\r\n")[1:]:

key, value = line.split(": ", 1)

headers[key] = value

headers["Location"] = "ws://%s%s" %(headers["Host"], self.path)

print headers

key1 = headers["Sec-WebSocket-Key1"]

key2 = headers["Sec-WebSocket-Key2"]

if len(data) < 8:

data += self.conn.recv(8-len(data))

key3 = data[:8]

self.buffer = data[8:]

token = self.generate_token(key1, key2, key3)

handshake = '\

HTTP/1.1 101 Web Socket Protocol Handshake\r\n\

Upgrade: WebSocket\r\n\

Connection: Upgrade\r\n\

Sec-WebSocket-Origin: %s\r\n\

Sec-WebSocket-Location: %s\r\n\r\n\

' %(headers['Origin'], headers['Location'])

self.conn.send(handshake + token)

self.handshaken = True

print 'Socket %s Handshaken with %s success!' %(self.index, self.remote)

sendMessage('Welcome, ' + self.name + ' !')

else:

self.buffer += self.conn.recv(64)

if self.buffer.find("\xFF") != -1:

s = self.buffer.split("\xFF")[0][1:]

if s == 'quit':

print 'Socket %s Logout !' %(self.index)

sendMessage(self.name + ' Logout')

deleteconnection(str(self.index))

self.conn.close()

break

else:

print 'Socket %s Got msg: %s from %s!' %(self.index,s,self.remote)

sendMessage(self.name + ':' + s)

self.buffer = ""

def generate_token(self, key1, key2, key3):

num1=int("".join([digit for digit in list(key1) if digit.isdigit()]))

spaces1 = len([char for char in list(key1) if char == " "])

num2 = int("".join([digit for digit in list(key2) if digit.isdigit()]))

spaces2 = len([char for char in list(key2) if char == " "])

combined = struct.pack(">II", num1/spaces1, num2/spaces2) + key3

return hashlib.md5(combined).digest()

class WebSocketServer(object):

def __init__(self):

self.socket = None

def begin(self):

print "WebSocketSerber Start!"

self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.socket.bind(("10.3.18.105", 19887))

self.socket.listen(50)

global connectionlist

i = 0

while True:

connection, address = self.socket.accept()

username = address[0]

newSocket = WebSocket(connection, i, username, address)

newSocket.start()

conectionlist['connection'+str(i)] = connection

i = i + 1

if __name__ == "__main__":

server = WebSocketServer()

server.begin()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值