我正在使用 python 来实现一个简单的 websocket 服务器。我使用的握手来自http://en.wikipedia.org/w/index.php?title=WebSockets&oldid=372387414。
握手本身似乎有效,但是当我点击发送时,我收到一个 javascript 错误:
未捕获的错误:INVALID_STATE_ERR:DOM 异常 11
这是html:
<!doctype html>
<html>
    <head>
        <title>ws_json</title>
    </head>
    <body onload="handleLoad();" onunload="handleUnload();">
        <input type="text" id='input' />
        <input type="button" value="submit" onclick="handleSubmit()" />
        <div id="display"></div>
        <script type="text/javascript">
            function showmsg(str){
                display = document.getElementById("display");
                display.innerHTML += "<p>" + str + "</p>";
            }
            function send(str){
                ws.send(str.length);
                ws.send(str);
            }
            function handleSubmit(){
                input = document.getElementById('input');
                send(input.value);
                input.focus();
                input.value = '';
            }
            function handleLoad(){
                ws = new WebSocket("ws://localhost:8888/");
                ws.onopen = function(){
                    showmsg("websocket opened.");
                }
                ws.onclose = function(){
                    showmsg("websocket closed.");
                }
            }
            function handleUnload(){
                ws.close();
            }
        </script>
    </body>
</html>
这是python代码:
import socket
import threading
import json
PORT = 8888
LOCATION = "localhost:8888"
def handler(s):
    print " in handler "
    ip, _ = s.getpeername()
    print "New connection from %s" % ip
    request = s.recv(1024)
    print "\n%s\n" % request
    print s.getpeername()
    # send response
    response = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
    response += "Upgrade: WebSocket\r\n"
    response += "Connection: Upgrade\r\n"
    try:
        peername = s.getpeername()
        response += "Sec-WebSocket-Origin: http://%s\r\n" % peername[0] # % request[request.index("Origin: ")+8:-4]
    except ValueError:
        print "Bad Request"
        raise socket.error
    response += "Sec-WebSocket-Location: ws://%s\r\n" % LOCATION
    response += "Sec-WebSocket-Protocol: sample"
    response = response.strip() + "\r\n\r\n"
    print response
    s.send(response)
    while True:
        length = s.recv(1)
        print length
        if not length:
            break
        length = int(length)
        print "Length: %i" % length
        data = s.recv(length)
        print "Received: %s" % data
        print ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('localhost', PORT))
s.listen(5)
print "server is running..."
while True:
    sock, addr = s.accept()
    threading.Thread(target=handler, args=(sock, )).start()
有谁知道我在这里做错了什么?