3

I am interfacing with a server that requires some http communication at the beginning (handshake with GET's/POST's), but later switches to raw data packets over tcp. Raw packets are sent and received using the connection established with last 'GET' packet with 'connection: keep-alive' header. I have managed to read incoming data using response.raw._fp.read() and stream=True, but i can't find a way to send data back to server.

By raw packets I mean bytestream, without any method/url or headers.

resp = session.get(
    'http://server.server/test',
    stream=True
)

while True:
    try:
        header = resp.raw._fp._safe_read(8)
        if header[3]>0:
            data = resp.raw._fp._safe_read(header[3])
    except http.client.IncompleteRead:
        break

1 Answers1

0

Want you want to do is get the underlying socket from the connection that requests create, and fortunately you can do it for streaming connections.

import requests
import socket
r = requests.get('http://server.server/test', stream=True)
s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)

After that you can send data as with any other socket. Side note for non-streaming connections the file descriptor is cleaned up before the response object is returned so you could also implement this inside the "response" callback.

CodeSamurai777
  • 3,285
  • 2
  • 24
  • 42