Skip to content

Instantly share code, notes, and snippets.

@sidd-kishan
Forked from mthri/SocketClient.ino
Last active April 28, 2022 08:24
Show Gist options
  • Select an option

  • Save sidd-kishan/813009bea87e545e7d0e171a886796b7 to your computer and use it in GitHub Desktop.

Select an option

Save sidd-kishan/813009bea87e545e7d0e171a886796b7 to your computer and use it in GitHub Desktop.
esp8266 socket client and python socket server
import http.client
conn = http.client.HTTPConnection("localhost")
conn.request('GET', "/")
resp = conn.getresponse()
resp.chunked = False
def get_chunk_size():
size_str = resp.read(2)
while size_str[-2:] != b"\r\n":
size_str += resp.read(1)
return int(size_str[:-2], 16)
def get_chunk_data(chunk_size):
data = resp.read(chunk_size)
resp.read(2)
return data
respbody = ""
while True:
chunk_size = get_chunk_size()
if (chunk_size == 0):
break
else:
chunk_data = get_chunk_data(chunk_size)
print("Chunk Received: " + chunk_data.decode())
respbody += chunk_data.decode()
conn.close()
print(respbody)
#https://stackoverflow.com/questions/24500752/how-can-i-read-exactly-one-response-chunk-with-pythons-http-client
Share
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const uint16_t port = 8585;
const char *host = "SERVER-IP";
WiFiClient client;
void setup()
{
Serial.begin(115200);
Serial.println("Connecting...\n");
WiFi.mode(WIFI_STA);
WiFi.begin("USSID", "PASSWORD"); // change it to your ussid and password
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
}
void loop()
{
if (!client.connect(host, port))
{
Serial.println("Connection to host failed");
delay(1000);
return;
}
Serial.println("Connected to server successful!");
client.println("Hello From ESP8266");
delay(250);
while (client.available() > 0)
{
char c = client.read();
Serial.write(c);
}
Serial.print('\n');
client.stop();
delay(5000);
}
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 8585 ))
s.listen(0)
while True:
client, addr = s.accept()
client.settimeout(5)
while True:
content = client.recv(1024)
if len(content) ==0:
break
if str(content,'utf-8') == '\r\n':
continue
else:
print(str(content,'utf-8'))
client.send(b'Hello From Python')
client.close()
from http.server import HTTPServer, SimpleHTTPRequestHandler
PORT = 8080
class TestHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_PUT(self):
self.send_response(200)
self.end_headers()
path = self.translate_path(self.path)
if "Content-Length" in self.headers:
content_length = int(self.headers["Content-Length"])
body = self.rfile.read(content_length)
with open(path, "wb") as out_file:
out_file.write(body)
elif "chunked" in self.headers.get("Transfer-Encoding", ""):
with open(path, "wb") as out_file:
while True:
line = self.rfile.readline().strip()
chunk_length = int(line, 16)
if chunk_length != 0:
chunk = self.rfile.read(chunk_length)
out_file.write(chunk)
# Each chunk is followed by an additional empty newline
# that we have to consume.
self.rfile.readline()
# Finally, a chunk size of 0 is an end indication
if chunk_length == 0:
break
httpd = HTTPServer(("", PORT), TestHTTPRequestHandler)
print("Serving at port:", httpd.server_port)
httpd.serve_forever()
# PUT with "Content-Length":
#curl --upload-file "file.txt" \
# "http://127.0.0.1:8080/uploaded.txt"
# PUT with "Transfer-Encoding: chunked":
#curl --upload-file "file.txt" -H "Transfer-Encoding: chunked" \
# "http://127.0.0.1:8080/uploaded.txt"
#https://stackoverflow.com/a/63037533
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment