javascript - Python WebSocket 不工作

标签 javascript python html websocket

我尝试实现我的第一个 websocket 示例,但我无法让它工作。

我使用 python 网络服务器:

import threading
import socket

def start_server():
    tick = 0
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 1234))
    sock.listen(100)
    while True:
        print 'listening...'
        csock, address = sock.accept()
        tick+=1
        print 'connection!' 
        handshake(csock, tick)
        print 'handshaken'
        while True:
            interact(csock, tick)
            tick+=1


def send_data(client, str):
     #_write(request, '\x00' + message.encode('utf-8') + '\xff')
     str = '\x00' + str.encode('utf-8') + '\xff'
     return client.send(str)

def recv_data(client, count):
    data = client.recv(count)    
    return data.decode('utf-8', 'ignore')

def handshake(client, tick):
     our_handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+"Upgrade:         WebSocket\r\n"+"Connection: Upgrade\r\n"+"WebSocket-Origin: http://localhost:8888\r\n"+"WebSocket-Location: "+" ws://localhost:1234/websession\r\n\r\n"
     shake = recv_data(client, 255)
     print shake
     #We want to send this without any encoding
     client.send(our_handshake)

 def interact(client, tick):
     data = recv_data(client, 255)
     print 'got:%s' %(data)
     send_data(client, "clock ! tick%d" % (tick))
     send_data(client, "out ! %s" %(data))

 if __name__ == '__main__':
     start_server()

和 HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Web Socket Example</title>
    <meta charset="UTF-8">
    <script>
      window.onload = function() {
        var s = new WebSocket("ws://localhost:1234/");
        s.onopen = function(e) { s.send('Ping'); }
        s.onmessage = function(e) { alert("got: " + e.data); }
        s.onclose = function(e) { alert("closed"); }
      };
    </script>
    </head>
    <body>
      <div id="holder" style="width:600px; height:300px"></div>
    </body>
 </html>

当我将浏览器指向 http://localhost/websocket.html 时在 apache2 上

我收到以下错误:

python websocketserver.py
listening...
connection!
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:1234
Origin: http://localhost
Sec-WebSocket-Key: A4sVkUhjVlTZbJrp2NUrqg==
Sec-WebSocket-Version: 13


handshaken
got:
Traceback (most recent call last):
  File "websocketserver.py", line 43, in <module>
    start_server()
  File "websocketserver.py", line 17, in start_server
    interact(csock, tick)
  File "websocketserver.py", line 40, in interact
    send_data(client, "out ! %s" %(data))
  File "websocketserver.py", line 24, in send_data
    return client.send(str)
socket.error: [Errno 32] Broken pipe

有人可以帮我解决这个问题吗?

谢谢

最佳答案

您正在使用较旧的 Hixie 75 协议(protocol)进行响应,但客户端仅使用较新的 HyBi/IETF RFC 6455 WebSocket 协议(protocol)。

您对握手的响应应该看起来更像这样(接受值是根据来自客户端的键值计算的):

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

在 HyBi/6455 中,帧不再用\x00 和\xff 分隔。相反,每个帧都有一个 header ,其中包含几条数据,包括帧类型和有效负载长度。

参见 spec了解更多信息。或者更好的是,您可以引用和/或使用现有的 python WebSocket 实现,例如 pywebsocket , tornado ,或者我自己的项目websockify其中包含 websocket.py,这是一个通用的 websocket 服务器库。

关于javascript - Python WebSocket 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18008718/

相关文章:

javascript - Google Drive API v3 不列出文件/文件夹的指定元数据

javascript - 如何将 JSON 值从 Controller 传递到 Thymeleaf 中的 HTML?

python - 如何使用日志恢复 iPython 0.13.2 session

php - PHP 中 HTML head 的最佳实践

javascript - 如何在动态div和与之关联的动态按钮上添加点击功能

javascript - 安装app.js错误Node.js

Python:按顺序发送异步http请求并自动处理cookie?

python - 如何捕获并发.futures._base.TimeoutError

javascript - Knockout 绑定(bind),JSON 数据的可重用代码

html - 如何创建字幕效果?