1

I have at my django project a socket server django-socketio (that works normally), and i try to send message message for it by using the following code:

import socket
import json

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect(('127.0.0.1' , 9000))
data = {
    'username': 'avt',
    'password': 123,
    'amount': 100
}
message = json.dumps(data)
s.sendall(message)

And receive error:

<socket fileno=5 sock=127.0.0.1:9000 peer=127.0.0.1:58952>: Invalid HTTP method: '{"username": "avt", "amount": 100, "password": 123}'
1
  • 2
    As far as I can tell, you're sending raw data through a socket connected to a server expecting a valid HTTP request. Or am I missed something here ? Commented Aug 29, 2014 at 12:03

2 Answers 2

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}'
Sign up to request clarification or add additional context in comments.

Comments

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/).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.