1

私は python と websockets が初めてで、pywebsocket の使用方法についてもっと知りたいと思っています。

現在、pywebsocket パッケージの例を編集していますが、残念ながら、次のコードのエラーを理解できません。

_GOODBYE_MESSAGE = u'Goodbye'

def web_socket_do_extra_handshake(request):
    request.ws_stream.send_message("Welcome", binary=False) # Error line
    pass  # Always accept.

def web_socket_transfer_data(request):
    while True:
        line = request.ws_stream.receive_message()
        if line is None:
            return
        if isinstance(line, unicode):
            request.ws_stream.send_message("Sending", binary=False)
            request.ws_stream.send_message(line, binary=False)
            if line == _GOODBYE_MESSAGE:
                return
        else:
            request.ws_stream.send_message(line, binary=True)

接続が初期化されたときに「ようこそ」メッセージをクライアントに送り返したいと思っていました。しかし、ハンドシェイクからメッセージを送信すると、コード 1006で websocket が閉じられました

どうしてこんなことに?

ハンドシェイク中にデータを送信できないことが問題である可能性があると考えたので、次のように試しました。

_GOODBYE_MESSAGE = u'Goodbye'
welcome = True

def web_socket_do_extra_handshake(request):
    pass  # Always accept.

def web_socket_transfer_data(request):
    while True:
        if welcome:
            welcome = False
            request.ws_stream.send_message("Welcome !", binary=False)

        line = request.ws_stream.receive_message()
        if line is None:
            return
        if isinstance(line, unicode):
            request.ws_stream.send_message("Sending", binary=False)
            request.ws_stream.send_message(line, binary=False)
            if line == _GOODBYE_MESSAGE:
                return
        else:
            request.ws_stream.send_message(line, binary=True)

最初のケースでも 2 番目のケースでも成功しませんでした。何が間違っているのか説明していただけますか? ありがとうございました

PS: mod_pywebsocket を Apache のモジュール (スタンドアロンではない) として実行しています。私の python バージョンは 2.6.6 です。$python script_wsh.py構文エラーをチェックするために使用する両方のスクリプトを実行しようとしました

4

1 に答える 1

0

私の例でこのエラーを見つけました:

最初のコード

ハンドシェイク中にクライアントにメッセージを送信することはできません

web_socket_do_extra_handshake は、ヘッダーが正常に解析され、WebSocket プロパティ (ws_location、ws_origin、および ws_resource) が要求に追加された後、ハンドシェイク中に呼び出されます。ハンドラーは、例外を発生させることによって要求を拒否できます。

2番目のコード

おそらく、コードに悪いインデントがありました


Websocket ハンドラーをデバッグする最も簡単な方法は、websocket をデバッグ モードで実行することです。

# Run standalone server with "--log-level debug"
./standalone.py -p 12345 --allow-draft75 -d example --log-level debug

# For apache module version, add LogLevel directive to httpd.conf
LogLevel debug

Websockets を apache モジュールとして実行していますが、apache のエラー ログで解析 (およびその他の) エラーを確認できます

于 2013-02-28T21:11:55.543 に答える