4

最近我用python写websocket服务端,握手是OK的,服务端可以接受客户端发来的消息,但是这么连线,当服务端给客户端发消息的时候,服务端会遇到像破管子这样的错误,我仔细检查了代码,可以找不到路,谁能帮帮我?这是我的服务器代码。提前致谢!

def SendData(pData, client, add): 

    if(pData == False):  
        return False  
    else:  
        #pData = str(pData)
        pData = pData.encode("utf-8")  
    token = "\x81"  
    length = len(pData)  
    if length < 126:  
        token += struct.pack("B", length)  
    elif length <= 0xFFFF:  
        token += struct.pack("!BH", 126, length)  
    else:  
        token += struct.pack("!BQ", 127, length)  
    pData = '%s%s' % (token, pData)
    if client is not None: 
        #client.sendto(pData, add)
        client.send(pData) 
        time.sleep(0.5) 
    return True


def RecvData(nNum, client):

    try:  
        pData = client.recv(nNum)  
        if not len(pData):  
            return False  
    except:  
        return False  
    else:  
        code_length = ord(pData[1]) & 127  
        if code_length == 126:  
            masks = pData[4:8]  
            data = pData[8:]  
        elif code_length == 127:  
            masks = pData[10:14]  
            data = pData[14:]  
        else:  
            masks = pData[2:6]  
            data = pData[6:]
        raw_str = ""  
        i = 0  
        for d in data:  
            raw_str += chr(ord(d) ^ ord(masks[i%4]))  
            i += 1  
    return raw_str


class WebSocket(threading.Thread):

    def __init__(self, conn, remote, path="/"):
        threading.Thread.__init__(self)
        self.conn = conn
        self.remote = remote
        self.path = path
        self.buffer = ""

    def generate_key(self, raw_key):
        return base64.b64encode(hashlib.sha1(raw_key.replace(" ", "")+\
        '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest())    

    def run(self):
        print 'Socket Start!'
        headers = {}
        self.handshaken = False
        while True:
            if self.handshaken == False:
                print 'Socket Start Handshaken with %s!' % str(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"].replace(" ", ""), self.path)
                    key = self.generate_key(headers["Sec-WebSocket-Key"])
                    print key
                    handshake = 'HTTP/1.1 101 Switching Protocols\r\n\
Upgrade: websocket\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Accept: %s\r\n\
Sec-WebSocket-Origin: null\r\n\
Sec-WebSocket-Location: %s\r\n\r\n\
                    ' %(key, headers["Location"])
                    print handshake
                    self.conn.send(handshake)
                    self.handshaken = True
                    print 'Socket Handshaken with %s success!' % \
                    str(self.remote)
            else:
                    receive = RecvData(64, self.conn)
                    print type(receive)
                    print receive
                    time.sleep(0.5)
                    #self.conn.send('hello')
                    SendData('This is from server!', self.conn, self.remote)
                    receive = ""


class WebSocketServer(object):

    def __init__(self):
        self.socket = None

    def begin(self):
        print "WebSocketServer Ready!"
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(("192.168.71.128", 9876))
        self.socket.listen(50)
        while True:
            conn, add = self.socket.accept()
            newSocket = WebSocket(conn, add)
            newSocket.run()

if __name__ == "__main__":
        server = WebSocketServer()
        server.begin()
4

0 回答 0