ECONNABORTED when attempting to connect ESP32 and ESP8266 - python

I'm attempting to connect an ESP32 and ESP8266 via sockets with micropython. I cannot get the ESP8266 client to connect to the ESP32 server without throwing an ECONNABORTED 103 error. Code is below, not sure what I'm doing wrong here. This seems to work when working off of my laptop and had no issues until trying to connect these two specific devies.
ESP32 Server Code:
import network
import socket
from time import sleep
SSID = 'esp'
KEY = 'meow'
ADDR = '192.168.4.1'
PORT = 2000
class socket_master:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(('',PORT))
self.attempt = 0
def accept_connection(self):
self.sock.listen(4)
self.conn, self.addr = self.sock.accept()
def test_speed(self):
data = 'attempt ' + str(self.attempt)
self.conn.sendall(data.encode())
self.attempt += 1
attempt = 0
try:
print('starting network')
ap = network.WLAN(network.AP_IF)
print('network started')
if ap.active() == False:
ap.active(True)
sleep(1)
ap.config(essid='esp')
print(ap.config('essid'))
print('set ssid')
print(ap.ifconfig())
except:
print('failed')
sm = socket_master()
sm.accept_connection()
print('waiting for client')
while True:
sm.test_speed()
ESP8266 Client Code:
# main.py -- put your code here!
import network
import socket
SSID = 'esp'
KEY = 'meow'
ADDR = '192.168.4.1'
PORT = 2000
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('esp')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
class socket_master_2:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((ADDR,PORT))
def receive_print(self):
data = self.sock.recv(1024)
print(data)
print(data.decode())
do_connect()
client = socket_master_2()
while True:
client.receive_print()

Related

Python socket library: OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected

OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
I am getting the above error..My server and client can send and receive their first messages but I get this error if I try to send more than one message.
My Server Code is here
import socket
import threading
import time
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5354
maxconnections = 9
ip = socket.gethostbyname(socket.gethostname())
print(ip)
server = (ip, port)
FORMAT = 'utf-8'
listensocket.bind((server))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
msg = f'\[ALERT\] {address} has joined the chat.'
lstbox.insert(0, msg)
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Client: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5986
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
And my client code is same with minor difference
import socket
import time
import threading
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5986
maxconnections = 9
ip = socket.gethostname()
print(ip)
FORMAT = 'utf-8'
host = 'MY_IP' # My actual ip is there in the code
listensocket.bind((host, port))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Server: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5354
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
Please let me know what changes are required to be made in order to make it run for every message.
I tried to put
g.connect((hostname, port))
the above line in the loop so that it will connect every time loop iterates. But it did not help.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
...
if at==0:
g.connect((hostname, port))
...
g.send(msg.encode())
at += 1
else:
...
g.send(msg.encode())
In the if at==0 condition it connects to the server, in the else part not. But is still trying to send something on the not connected socket.

Why does my Python P2P client works over LAN but not the Internet and how can I fix this

Why does my Python P2P client works over LAN but not the Internet and how can I fix this!
I would like to make a p2p messenger and I just don't know why the p2p functionality with UDP Hole Punching is not working. Please help!
Server:
This server holds peers ips and ports for the client.
The ping function pings the peers to check if they are still alive.
'''
import threading
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("IP_ADDRESS", 8081))
addrs = []
print('Server started...')
def ping(addr):
try:
sock.sendto(b'ping', addr)
sock.settimeout(1)
data, addr = sock.recvfrom(1024)
sock.settimeout(None)
return True
except Exception as ex:
sock.settimeout(None)
return False
while True:
data, addr = sock.recvfrom(1024)
print(addr)
sock.sendto((addr[0]+' '+str(addr[1])).encode(), addr)
for a in addrs:
p = ping(a)
print(p, a)
if p:
sock.sendto((a[0]+' '+str(a[1])).encode(), addr)
addrs.append(addr)
sock.sendto(b'DONE', addr)
'''
Client:
import threading
import socket
import time
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.addrs = []
self.chat_logs = ''
self.peers = ''
self.self_data = ('0.0.0.0', 0)
def recv_thread(self):
while True:
try:
data, addr = self.sock.recvfrom(1024)
if data == b'ping':
self.sock.sendto(b'pong', addr)
else:
data = data.decode()
new_user = True
for a in self.addrs:
if a == addr:
new_user = False
if new_user == False:
self.chat_logs += addr[0]+':'+str(addr[1])+' - '+data+'\n'
else:
self.chat_logs += addr[0]+':'+str(addr[1])+' joined the p2p network... \n'
self.addrs.append(addr)
except Exception as ex:
print(ex)
def send_msg(self):
message = self.messageBox.text()
if len(message) > 0:
self.chat_logs += 'You - '+message+'\n'
self.chatBox.setPlainText(self.chat_logs)
for a in self.addrs:
try:
self.sock.sendto(message.encode(), a)
except:
self.addrs.remove(a)
def get_peers(self, host):
host = host.split(':')
host = (host[0], int(host[1]))
self.sock.sendto(b'PEERS', host)
self.self_data, addr = self.sock.recvfrom(512)
self.self_data = self.self_data.decode().split()
self.self_data = (self.self_data[0], int(self.self_data[1]))
while True:
data, addr = self.sock.recvfrom(512)
if data == b'DONE':
break
else:
data = data.decode().split()
self.addrs.append((data[0], int(data[1])))
print(self.addrs)
for a in self.addrs:
try:
self.sock.sendto(b'join', a)
except:
self.addrs.remove(a)
t = threading.Thread(target=self.recv_thread)
t.start()
def connect_to_pears_network(self):
dlg = CustomDialog()
if dlg.exec():
text = dlg.message.text()
if len(text) > 6:
self.get_peers(text)
else:
pass
I hope I did this post right this is my first time making a post.

Python Sockets Port forwarding

So I port forwarded my ip so that my friends can test if my stuff works
And I have a simple server that is hosted on the internal ip
import socket
import threading
class Server:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connections = []
def __init__(self, ip="0.0.0.0", port=5555):
self.sock.bind((ip, port))
self.sock.listen(1)
def handler(self, c, a):
while True:
data = c.recv(4096)
for connection in self.connections:
connection.send(data)
if not data:
print(str(a[0]) + ":" + str(a[1]), "disconnected")
self.connections.remove(c)
c.close()
break
def run(self):
while True:
c, a = self.sock.accept()
rThread = threading.Thread(target=self.handler, args=(c, a))
rThread.daemon = True
rThread.start()
self.connections.append(c)
print(str(a[0]) + ":" + str(a[1]), "connected")
host = Server("192.168.x.xxx", 6667)
print("Server status: Running")
host.run()
And a simple client module that I attempted to pass the public ip to
import socket
import pickle
import threading
import pyaudio
import numpy as np
class Client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def __init__(self, address):
threading.Thread.__init__(self)
self.sock.connect((address, 6667))
def run(self, id):
RATE = 16000
CHUNK = 256
self.id = id
p = pyaudio.PyAudio()
player = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True, frames_per_buffer=CHUNK)
while True:
data = self.sock.recv(4096)
data = pickle.loads(data)
if data[0] != self.id:
if not data:
break
player.write(np.fromstring(data[1],dtype=np.int16),CHUNK)
def sendMsg(self, data, id):
data1 = [id, data]
self.sock.send(pickle.dumps(data1))
The client does not connect to the server when I try to give it the public address
print("Connecting to server")
cli = Client("91.242.xxx.xxx")
rThread = threading.Thread(target=cli.run, args=(id,))
rThread.daemon = True
rThread.start()
print("Connected to server")
The only thing that outputs is Connecting to server
I am not sure what I am doing wrong or what to do to fix this
My ISP uses CGNat and I just had to call them to tell them that I need a public IP and they gladly did it for me.

Problem with pickle.loads() - ran out of input

I'm trying to make a small multiplayer game and thus need to send objects. Have created server and client and everything is working for sending bytes e.g. (str("").encode(utf-8)).
But when I tried to use pickle I've started bumping into issues. Have I made any mistakes below?
Server.py:
import socket
import threading
import pickle
HEADER = 8 #Contains info about incoming msg SIZE! first 8 bytes contains size
FORMAT = "utf-8"
PORT = 5558
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
DISCONNECT_MSG = "!Disconnect"
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(ADDR)
def handle_client(client_socket, client_addr):
print(f"[NEW CONNECTION] {client_addr} connected!")
while True:
try:
msg = pickle.loads(client_socket.recv(2048))
print(f"[RECEIVED] {client_addr} - {msg}")
if msg == DISCONNECT_MSG:
print(f"[DISCONNECTED] client {client_addr} has disconnected")
client_socket.close()
return False
except socket.error as e:
print(e)
def start_server(server):
server.listen()
print("[STARTED] server is online!")
while True:
client_socket, client_addr = server.accept()
thread = threading.Thread(target=handle_client, args=(client_socket, client_addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start_server(server_socket)
Client.py
import socket
import pickle
HEADER = 8
FORMAT = "utf-8"
PORT = 5558
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
DISCONNECT_MSG = "!Disconnect"
class Client:
def __init__(self):
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect_to_server(self, server_address):
"""
:param server_address: tuple(IP, PORT)
:return:
"""
self.get_client_socket().connect(server_address)
def get_client_socket(self):
return self.client_socket
def send_object(self, object):
msg = pickle.dumps(object)
self.get_client_socket().sendall(msg)
client = Client()
client.connect_to_server(ADDR)
d = "1"
client.send_object(d)
#client.send_object(DISCONNECT_MSG)
I've also tried to put while loop into send_object() but then after couple of successful receivements I get:
msg = pickle.loads(client_socket.recv(2048))
_pickle.UnpicklingError: invalid load key, '\x00'.
After some research it appears that before trying to unpickle an object you first need to check if received message is not None. Because server is constantly trying to receive message from client, but that is another issue.
Code modification in server.py:
def handle_client(client_socket, client_addr):
print(f"[NEW CONNECTION] {client_addr} connected!")
while True:
try:
msg = client_socket.recv(2048)
if msg:
new_msg = pickle.loads(msg[HEADER:])
print(f"[RECEIVED] {client_addr} - {new_msg}")
if msg == DISCONNECT_MSG:
print(f"[DISCONNECTED] client {client_addr} has disconnected")
client_socket.close()
return False
except socket.error as e:
print(e)
Note -> Until DISCONNECT message is not sent from client it will use much processor time (issue mentioned above)

Python Socket Program - NameError: name 'self' is not defined. I changed the localhost, ports etc but this error refuses to go away

import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
husainshoab#hs-Len:~$ python IOTDeviceSocket.py
Traceback (most recent call last):
File "IOTDeviceSocket.py", line 7, in
class ClientSocket:
File "IOTDeviceSocket.py", line 11, in ClientSocket
self.soc = None
NameError: name 'self' is not defined
There appears to be nothing wrong with your code. I just used it to create a simple test application
# ClientSocket.py
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
cs = ClientSocket()
cs.start_client()
cs.send_to_Server('Hello')
cs.receive_from_Server()
here's a simple test server which just spits back some JSON data
# test_server.py
import socket
from datetime import datetime
import json
def logMessage(clientMessage):
logTime = datetime.today();
msg = "{} | {}\n".format(logTime, clientMessage)
print msg
TCP_PORT = 8000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', TCP_PORT))
# listen() puts the socket into server mode,
server.listen(1)
while True:
# wait for an incoming connection
connection, address = server.accept()
try:
# receive data in chunks of 64 bytes
while True:
data = connection.recv(64)
# how do we know if we received all the data?
if data:
# we received data from the client, log it to the file
logMessage(data)
response = {
'name' : 'Jonathan Swift',
'occupation' : 'author'
}
jsonResponse = json.dumps(response)
messageLength = len(jsonResponse)
bytesSent = 0
# send a response to the client after turning our dict into
# a JSON string
while(bytesSent < messageLength):
sent = connection.send(jsonResponse)
bytesSent += sent
else:
# no data, break out of receiving loop
break
except Exception as e:
raise
finally:
connection.close()
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
soc = None
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
you should define the soc variable after class statement so that you can use it globally.

Categories