第一条消息始终出错

时间:2011-03-26 05:41:51

标签: javascript python html5 websocket

目前我正在设置基本的WebSockets脚本。我可以让客户端连接到服务器,但是每当服务器将第一条消息发送到客户端时,客户端就会注册并发生错误,并且我可以告诉readyState是打开的,并且应该允许消息通过。消息具有/ x00和/ xff的正确开头。我无法弄清楚出了什么问题。

编辑:以下是似乎导致错误的代码。 data.js只保存Python服务器用于设置服务器的内容,因此我只需要在测试时更改一个文件并且端口尚未超时。

客户端:

<html>
<head>
<script type="text/javascript" src="data.js">
</script>
<script type="text/javascript">
var ws, error
init = function() {
  ws = new WebSocket("ws://127.0.0.1:"+port+"/websockets/main.py")
  ws.onopen = function() {
    console.log("Connected")
    log("Connected")
  }
  ws.onmessage = function(e) {
    console.log("Received data")
    log(e.data)
  }
  ws.onerror = function(e) {
    console.log(e)
    ws.send("Error occurred. Resend")
  }
}
log = function(msg) {
  document.getElementById("log").appendChild(document.createElement("br"))
  document.getElementById("log").innerHTML = document.getElementById("log").innerHTML+msg
}
</script>
</head>
<body onload="init()">
<div id="log">
</div>
</body>
</html>

服务器端:

import threading, hashlib, socket, time, re, struct

class WebSocketThread(threading.Thread):
  def __init__(self, channel, details, websocket):
    self.channel = channel
    self.details = details
    self.websocket = websocket
    threading.Thread.__init__(self)

  def run(self):
    print("> Received connection ", self.details[0])
    self.handshake(self.channel)
    while True:
        self.interact(self.channel)

  def finduser(self, client):
    for user in self.websocket.users:
      if user.socket == client:
        return user
        return 0

  def send_data(self, user, data):
    user.socket.send(self.wrap(data))
    print ("> Sent data", data, "to", user)

  def recv_data(self, client, count):
    data = client.recv(count)
    return data

  def handshake(self, client):
    shake = self.recv_data(client, 256)
    our_handshake = self.create_response(shake)
    client.send(our_handshake)
    print ("> Accepted client ", self.finduser(client))
    self.send_data(self.finduser(client), "Test")

  def interact(self, client):
    users = self.websocket.users
    this_user = self.finduser(client)
    data = self.unwrap(self.recv_data(client, 256))
    print ("> Received data ", data, "from", this_user)

  def create_response(self, data):
    key3 = ""
    lines = data.splitlines()
    resource = re.compile("GET (.*) HTTP").findall(data)
    resource = resource[0]
    for line in lines:
      parts = line.partition(": ")
      if parts[0] == "Host":
        host = parts[2]
      elif parts[0] == "Origin":
        origin = parts[2]
      elif parts[0] == "Sec-WebSocket-Key1":
        key1 = parts[2]
      elif parts[0] == "Sec-WebSocket-Key2":
        key2 = parts[2]
      key3 = line
    spaces1 = key1.count(" ")
    spaces2 = key2.count(" ")
    num1 = int("".join([c for c in key1 if c.isdigit()]))/spaces1
    num2 = int("".join([c for c in key2 if c.isdigit()]))/spaces2
    token = hashlib.md5(struct.pack(">II8s", num1, num2, key3)).digest()
    return "HTTP/1.1 101 WebSocket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Origin: %s\r\nSec-WebSocket-Location: ws://%s%s\r\nSec-WebSocket-Protocol: sample\r\n\r\n%s\r\n"% (origin, host, resource, token)

  def unwrap(self, data):
    return data[1:-1]

  def wrap(self, data):
    return ("\x00"+data+"\xff")

1 个答案:

答案 0 :(得分:0)

尝试删除令牌后的最后一个\ r \ n:

return "HTTP/1.1 101 WebSocket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Origin: %s\r\nSec-WebSocket-Location: ws://%s%s\r\nSec-WebSocket-Protocol: sample\r\n\r\n%s"% (origin, host, resource, token)

我相信它会解决你的问题:)