[Answered ]-Python socket send message Invalid HTTP

2👍

You are talking to a WebSocket server. Therefore you need to use the WebSocket protocol.

Your code sends the following string to the server:

{"username": "avt", "amount": 100, "password": 123}

but you actually need to send something like this (which begins the protocol handshake):

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:9000
Origin: http://127.0.0.1:9000
Sec-WebSocket-Key: gCJZxvFvQ2Wa/flhLUvAtA==
Sec-WebSocket-Version: 13

The above request was generated using websocket-client with this code:

import json
import websocket

ws = websocket.WebSocket()
ws.connect('ws://127.0.0.1:9000/')
ws.close()

You can experiment with a WebSocket echo server:

ws.connect('ws://echo.websocket.org/')
# now you can send data...
data = {
    'username': 'avt',
    'password': 123,
    'amount': 100
}

>>> ws.send(json.dumps(data))
57
>>> ws.recv()
'{"username": "avt", "amount": 100, "password": 123}'
👤mhawke

0👍

Your django app expects valid HTTP requests (as described here : http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html), not a mere json dump. So you either need to manually write a (correct) full blown HTTP request, or use some higher level tool like the stdlib’s urllib or, even better, the third-part “requests” lib (http://docs.python-requests.org/en/latest/).

Leave a comment