#networks
1 messages ยท Page 17 of 1
its UDP
and its client side
@tall olive do you have to bind for all UDP sockets even if they are client side or something?
ok
this example is wrong then: https://pythontic.com/modules/socket/udp-client-server-example
UDP client-server example in python make use of socket objects created with SOCK_DGRAM and exchange data with sendto(), recvfrom() functions
so i'm not sure if it's different on windows
on linux if don't explicitly bind but you sent to something you'll get an ephemeral port implicitly
that is usually what happens
but that doesn't happen if you just recv
but recvfrom on linux still just block on linux despite not having a port
i'm not sure if windows treats it differently
its weird, because it works fine on the server
seems to confirm you either need to bind or send first
are you binding on the server?
tcp gives you a port on bind or connect
udp gives you a port on bind or send, not recv
oh ok
if you send something first you'd get a port
hmm, so should I just send a dummy "connected" packet or something?
well it's a weird model to have a client that receives unsolicited packets
im currently using both a TCP and UDP socket
so the TCP socket will connect, then they will both listen on seperate threads
how do you know how to get the packet to the udp socket?
what port are you sending to?
same port
no
im pretty sure you can use TCP and UDP sockets on the same port
im probably going about this a very incorrect way lol
yeah, but you're not binding ๐
if you want to use that port, what is your objection to binding?
if you don't bind you would get an ephemeral port when you send your connect packet
would there be a way to tell what port the TCP socket has bound to?
the udp socket isn't going to just share a port with the tcp socket
you have to explicitly bind to a port if you want to have a consistent port
ok
another option is to communicate back the ephemeral port
this could be what your connect message does
but the sender needs to know the port to send you something
and that will either be the port you bind to or the ephemeral port you get when you send a message
so, for the Client, I should have two sets of addresses: the local address to bind to and the global address to connect to?
I apologise if im being really stupid, im fairly new to networking and have never worked with UDP
no worries, not stupid, just learning
normally a client isn't going to have a static port because you don't know what ports will be in use in a client system
im thinking that I could run port = socket_tcp.getsockname()[1] and bind the UDP socket to that
I am 99% sure that I can bind a TCP and UDP socket to the same port, as this is done in games like minecraft (25565 is UDP and TCP at the same time)
but you could do something like
sock.bind(("0.0.0.0", 0))
_, port = sock.getsockname()
or, I guess just do socket_udp.bind(socket_tcp.getsockname())
and communicate that back to the server
what would 0.0.0.0:0 be?
right but what if that port is in use?
0.0.0.0 says to listen on all interfaces
and port 0 says to get any port available on the system
or you binding to a static port on tcp?
or just connecting to a server?
im only running connect on the tcp port, so that is being assigned an ephemeral port
would that port have a chance of already being used by UDP?
right, so there's nothing to say that tcp port isn't in use for udp by another application
huh
you can't just assume an ephemeral port is not going to be in use
fair enough
is there anyway I can get one that definately isnt?
or will it have to be a static port?
bind to 0
ok
that will get you a port that's not in use
by both protocols?
no
oh
i'm not sure there's any atomic way to ask for a port that's not in use by both protocols
for servers you'd just use a static port. for clients you could just get an ephemeral port on each and send a message over either protocol informing the server of the client port
how would the server be able to identify who the UDP packet is from?
should I make UUIDs or something?
send it over the tcp connection
or send the tcp port in the udp connection
but i'd probably to the former
since you have the established trust of the persistent connection
yeah
gotta run to get some lunch. good luck!
ty for your help ๐ @tall olive
This is what I'm currently doing: ```py
self._socket_udp = socket.socket(
socket.AF_INET, socket.SOCK_STREAM
)
self._socket_udp.bind("0.0.0.0:0")
_, port = self._socket_udp.getsockname()
self.send("_assign_udp_port", {"port": port}, network_protocol=TCP)
could someone help me implement a method into my network?
i have to do something like this:
If the training set is empty, raise EmptySetException
for epoch in range(epochs):
prime the data using the specified order
while training set is not exhausted:
get a feature and label pair from the dataset
present the feature list to the input neurodes
check the values at the output neurodes and calculate the error
present the expected values to the output neurodes
make any necessary report
report the final RMSE
Hey @tall olive, super sorry to ping you but I'm getting a completely new error now:```py
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
what does the code look like for the send?
i mean, Im sending the port assignment via TCP so I dont think that should be the problem.
the error is actually coming from socket_udp.recvfrom(buffer)
should I run socket.listen?
this is an example of the address that would be assigned: ('0.0.0.0', 61203)
Here is the send code, if you do need it tho:```py
def send(self, protocol: str, data: dict = None, network_protocol: int = TCP):
if network_protocol != self.TCP and network_protocol != self.UDP:
raise TypeError("Invalid network_protocol type. Must be TCP or UDP.") # noqa: E501
if data is None:
data = {}
message = pickle.dumps({
"protocol": protocol,
"data": data
})
header = bytes(f"{len(message):<{self._header_size}}", "utf-8")
if network_protocol == self.TCP:
self._socket_tcp.sendall(header + message)
else:
address = (self._address, self._port)
self._socket_udp.sendto(header + message, address)
do you have more of the traceback and the connection and recv code?
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Lenny\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
Choose Username: self.run()
File "C:\Users\Lenny\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "c:\users\lenny\onedrive\projects\jank-engine\jank\networking\client.py", line 136, in _socket_thread
header_bytes, c_address = self._socket_udp.recvfrom(self._header_size) # noqa: E501
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
def connect(self, address: str, port: int, enable_udp: bool = False):
self._address = address
self._port = port
self._socket_tcp = socket.socket(
socket.AF_INET, socket.SOCK_STREAM
)
while True:
try:
self._socket_tcp.connect((self._address, self._port))
break
except TimeoutError:
print("Server did not respond, retrying.")
socket_thread_tcp = threading.Thread(
target=self._socket_thread,
daemon=True
)
socket_thread_tcp.start()
if enable_udp:
self._socket_udp = socket.socket(
socket.AF_INET, socket.SOCK_STREAM
)
self._socket_udp.bind(("0.0.0.0", 0))
_, port = self._socket_udp.getsockname()
self.send("_assign_udp_port", {"port": port})
socket_thread_udp = threading.Thread(
target=self._socket_thread,
daemon=True,
kwargs={"network_protocol": self.UDP}
)
socket_thread_udp.start()
self.connected = True
self.udp_enabled = enable_udp
self.on_connection(self._socket_tcp)
is the recv happening in the socket thread?
yup
mind sharing that as well?
sure
1 min
should I just send the entire file? the socket thread is larger than 2000 characters :P
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
might be worth just sharing the whole thing
ok
note that the majority of the code is experimental and ill refine it once I have something working
no worries ๐
anyone think they could help me with this project im working on
i have to implement a method using two other classes
@ember ledge
if enable_udp:
self._socket_udp = socket.socket(
socket.AF_INET, socket.SOCK_STREAM
)
notice anything wrong there?
FUCK
i must have changed it to TCP to test something and forgot to change it back
sorry for wasting your time ๐
wanna test it real quick just to confirm that was def it?
Ok, I'm getting a slight problem where the port that socket.getsockname() gives is different to the one the server sees. So, the client will tell the server that the port is something like 52882, but when the client tries to send a packet via UDP, the server sees that address's port as 1031. I expect this is something to do with the local port and real port being different, but how can I get what the real port would be from the client side?
The same thing happens with TCP ports, the port the client thinks it is on is different to the port the server receives from
can you clarify how you're seeing the port as 1031? is that the address you see when you recvfrom or if you call getsockname on the socket on the server side
That is the address the the server gets from recvfrom
52882 is the port the client gets from getsockname
basically, getsockname is giving a different port to the one the server thinks the messages are from
hmm, that's not my experience testing locally 
one sec, lemme open a port on a server so i can test something
ok
the left side is the server, the right side is the client
the client first prints the TCP socket name, which is correct as you can see on the left.
the client then prints the UDP socket name and sends it to the server, these also match.
the server saves the UDP socket name to a dictionary for later.
the client then starts sending packets to the server, and prints the client's UDP address every time. This is still the same as before.
the server receives these packets, but the port number is different to what was sent earlier, so the server does not recognise it and prints a debug log
ok, I just tested by connecting to my public IP instead of my dynamic dns server, and I still get the same issue so it cant be a problem there
hmm, i just tested this across servers and it worked as expected
any idea what could be happening?
>>> import socket
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> sock.bind(("0.0.0.0", 0))
>>> sock.getsockname()
('0.0.0.0', 59265)
>>> sock.recvfrom(1024)
('hello', ('10.20.0.2', 33358))
>>> sock.sendto("hello", ('10.20.0.2', 33358))
5
and
>>> import socket
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> sock.sendto("hello", ("10.20.0.19", 59265))
5
>>> sock.recvfrom(1024)
('hello', ('10.20.0.19', 59265))
ill try running that
is the code the same as what you shared earlier?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
that's good to confirm i'm not crazy ๐
though weird that it'd work local 
ikr
@ember ledge what's sending the udp packets from the client to the server?
i don't see any code in the client that would be doing udp sends
yeah, that is just the class that the user would inherit from
i can send you the example im using to test?
one thing i'd be curious about is if when you send the port over tcp if you also send a udp message at the same time for debugging
like just send over both tcp and udp and see if they match at that point
Client Example: https://paste.pythondiscord.com/apafuzojun.rb
Server Example: https://paste.pythondiscord.com/uyorufixek.rb
wait why does it think it is a ruby file
jank.networking 
lol
when you dont know what to call your game engine but you know its full of bugs
like just send over both tcp and udp and see if they match at that point
@tall olive they match
now im even more confused lol
Btw, I really appreciate you helping me out here, I have no idea what I'd be doing otherwise
you sure you don't have some old client just pinging messages at the server running somewhere? ๐
i like network programming so it's a fun mystery
im pretty sure, cos the server isnt receiving the Clients controls
is this running on a linux host?
ah, i don't know how to troubleshoot from the os level on windows
no worries, just wanted to check what the os sees
to see if it's opening a second socket
ok
you sure you don't have some old client just pinging messages at the server running somewhere? ๐
i think you where right
i just tested, and its suddenly working
i only asked because it's a mistake we all make a thousand times
it is the minecraft port, so maybe something was trying to connect
ah, interesting
(its the only port i have forwarded)
always a good exercise to have your understanding of a technology challenged
no problem. looks like a fun project
and i'm sure you're learning a lot of cool stuff ๐
yeah, its just a little side project, hopefully itll get rid of the requirement for too much boilerplate code when making games in the future
and i'm sure you're learning a lot of cool stuff ๐
@tall olive for sure, ive never touched networking since this project and I find it super interesting
nice. it's a super useful part of the stack to learn. demystifies how much of the internet technologies work
yeah, anyways, now that i have it all sorted out, if I want to send a packet via UDP i literally only have to change a kwarg. I do worry about blackboxing it too much tho
yeah, it's nice having abstractions to make that stuff easier
the python socket api is very close to C so there's not a lot of modern ergonomics on top of it
it's like the bare minimum of making the C apis object based
yeah, I did actually use some old C SO posts that helped me out
right, lets see how many clients I can add before something breaks >:)
gn, and thanks again for all your help! @tall olive
How do I check is a address:port is accessible?
currently I use this code
def check_ip(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = (ip, int(port))
s.settimeout(10)
try:
s.connect(host)
s.shutdown(socket.SHUT_RDWR)
s.close()
return True
except Exception as e:
print(e)
try:
s.shutdown(socket.SHUT_RDWR)
s.close()
except Exception as e:
print(e)
return False```
but it seems after a while it gets weird and saying that host is offline when it's not
maybe you can try putting in into a loop that continously tries to connect and disconnect
just saying
I don't know how to do it
but I just told my opinion
@modern oriole
I see
yep
is there a way to get requests to use the windows certificate store?
i found this https://stackoverflow.com/a/50215614/2954547 but it only applies to specific domains
obviously thats fine if im only using the session to query one domain at a time, but itd be better to have it apply for all domains
hello
im trying to connect to a minecraft server using FTP to get usercache.jsonm
but im getting this
'NoneType' object has no attribute 'sendall'
I assumed this was because my file isnt in the directory
but I dont know how to see all the directories to look in
@fathom condor do you mean that your problem is that you are not able to find the minecraft dir??
or something else
ohh
ftp = FTP('eu~~~.~~~~~~host.com')
ftp.login(user="~~~~~~~~@~~~~~~~~~", passwd="~~~~~~809.")
ftp.cwd("/")
def usercache():
filename = '/usercache.json'
localfile = open(filename, "wb")
ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
ftp.quit()
return filename
'NoneType' object has no attribute 'sendall'
so it is that minecraft dir na??
no
ohh I get it
its a pebblehost server
you are not able to find that userchache thing
well that I don't know
use pickle if it's binary file
it may help
yes
use pickle
it may help
and if it doesn't
then I don't know
but using pickle would good
in binary files
@empty solstice
yes
I have the full adress for the file i need
gg
how do I use pickle for that?
no not for that
?
for sending or reading something in the file
oh
yes
maybe sending the elements or blocks is a problem that the program is not doing very well
so for that I said use pickle
Why ftp? It's a fairly broken protocol
The fact that is a . JSON makes me think there is an API for it
And or, if you have to have the file, scp
See paramiko
Unless you are running the server on windows, that if a little trickier
SFTP works good as well
@fathom condor can you share a full traceback
also the rest of your code. are you calling usercache multple times?
Hey so when using socket lib, every time the server ends with running. My client is stuck in an infinite try: except: loop where i cant ctr c out of it. I figured it is because of this line of code:
data, addr = client.recvfrom(1024)
Im using the socket library. Does anyone know how to fix this?
Whats your full code
@fathom condor I bet you're calling usercache multiple times and usercache is closing the ftp connection after the first time
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.setsockopt(socket.SQL_SOCKET, socket.SO_BROADCAST, 1)
client.bind(("", 37020))
while True:
data, addr = client.recvfrom(1024)
print(f"received message: {data}")
@gloomy root
But i think its because of a try except loop in the socket module
Use a time out
@thorn stratus could you pls send an example
use this to set a timeout
then use a try/except to catch the time out error and try to recieve again if it gets a socket.timeout, or break out of the program if it gets a KeyboardInterrupt
Thanks
client:
import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP_address = "192.168.0.102"
Port = 8888
try:
server.connect((IP_address, Port))
except:
print("An error appeared!")
def messages():
while True:
command = server.recv(1024).decode()
print(command)
while True:
threading.Thread(target=messages).start()
```
server:
```py
import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("192.168.0.102", 8888))
server.listen(2)
client_sockets = []
def sendallclients(message):
for x in client_sockets:
try:
x.send(message)
except:
client_sockets.remove(conn)
def sendd():
while True:
message = input(">>> ").encode()
sendallclients(message)
while True:
conn, addr = server.accept()
client_sockets.append(conn)
print(str(addr[0]) + " has connected succesfully!")
threading.Thread(target=sendd).start()
conn.close()
server.close()
my friend got a timeout error
does the client work on the machine running the server
yes
ya
show me the port forward rule
hey guys i need a hand in some really basic stuff i'm building, i have a little "server" which accepts connections and assigns them a thread and it logs user messages (along with some commands but those are unimportant and very basic) but even though assigning a thread to each connession should let me handle moer than 1 connection at a time, if i do start() twice and open two clients only one client manages to talk to the server for some reason...
should i like send the code?
@ember ledge is your friend connecting to 192.168.0.102?
that's an internal IP on your network
go to https://www.whatismyip.com/ and your friend will have to use that IP on the client
you can use ngrok to connect with people outside of your network as if you were a localhost iirc, i don't know all the specifications but yeah
@undone gust would need to see code
Hey @undone gust!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
yeah, use a pastebin like the bot suggested
this pastebin looks cool af 
yeah don't mind the fact that the command to shut the pc off doesn't work, it's disabled for now
oh also besides finding the problem if you have any suggestions like "best practice" or better methods i could have done it with please share them with me i just started this whole socket stuff but i'm looking to get better at it hopefully
go to https://www.whatismyip.com/ and your friend will have to use that IP on the client
@tall olive so i have to leave that192.168.0.102on the server.py?
i just put my public ip in the client
and it still works
@ember ledge yea, you need to kick your local ip on the server
your router will forward to that ip
bruh im so confused
Mood.
@undone gust
thread = threading.Thread(target=handle_client(conn, addr))
you're calling the function
so it blocks there
wdym
that needs to be
thread = threading.Thread(target=handle_client, args=(conn, addr))
oh god i want to kick myself, in the tutorial i was watching they did like you told me to
you're calling handle_client so it spins that function up in the local thread
but i noticed it worked the same
so i decided to make it shorter
you're calling handle_client so it spins that function up in the local thread
@tall olive what does this mean? sorry i'm a little confused
also you want to add
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
so that you can reuse the port when the server crashes
wdym reuse the port
that'l l get rid of
OSError: [Errno 98] Address already in use
if you try to start it after the server crashing
oh like if i start the server program again without closing it first?
yeah
or..
idk i just started it and created an error so it crashed but i opened server.py again and it worked fine
without adding that
anyways imagine this
handler = handle_client(conn, addr)
thread = threading.Thread(target=handler)
can you see what that doesn't work?
yeah because it has no arguments
yo guyss
@ember ledge no problem ๐
@undone gust it's not about the args, that's the same as what you were doing
just broken across two lines
to demonstrate how it wasn't creating a thread
glad it works ๐
when you create a thread you pass a reference to the function and the args separately
oh so targert=handle_client(conn, addr) creates like a variable of handle_client but without actually providing stuff?
then the thread started up and runs your function inside the thread
oh i just got it
it's nt that it doesnt create it
its that it creates it without creating a thread
so it blocks the code
right
it's trying to pass the result of your function (which would be None) to the target of thread creation
ohhh
but it just blocks because it the while loop
and it worked because meanwhile its still running it?
right
yeah yeah got it
i have to leave now but can i dm you about the other part in like 5 mins?
the one about the error
i prefer to help here so others can help and learn and search and such
but feel free to ping if i'm not around
ay @undone gust
my friend got this error
he sent this sc
import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP_address = "192.168.0.102"
Port = 8888
server.connect((IP_address, Port))
def messages():
while True:
command = server.recv(1024).decode()
print(command)
while True:
threading.Thread(target=messages).start()
here's client's code
@ember ledge client? Why is the function your trying to start a new thread for (on the server) on the client?
And besides you should do target=(messages), args=() I THINK
What's the server code?
Or at least the messages function +when you start the thread
import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("192.168.0.102", 8888))
server.listen(2)
client_sockets = []
def sendallclients(message):
for x in client_sockets:
try:
x.send(message)
except:
client_sockets.remove(conn)
def sendd():
while True:
message = input(">>> ").encode()
sendallclients(message)
while True:
conn, addr = server.accept()
client_sockets.append(conn)
print(str(addr[0]) + " has connected succesfully!")
threading.Thread(target=sendd).start()
conn.close()
server.close()
Try doing threading.thread(target=(sendd), args=()).start()
And then tell me what happens
while True:
threading.Thread(target=messages).start()
you're just starting an infinite number of threads in a tight loop
Also shouldn't yoi assign it
Like test = threading.thread etx
you likely ran out of available threads
you need to call server.accept and only start new threads when you accept a new connection you don't need multiple threads on the client
Wait why do you create a thread on the client
also that ^ heh
Yay
i need to receive every message i send on server
the client doesn't need to spin up threads for that though
just remove the while True: and all the thread creation and just call messages()
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP_address = "public ip"
Port = 8888
server.connect((IP_address, Port))
def messages():
while True:
command = server.recv(1024).decode()
print(command)
messages()
ya
general code review
oh, i literally deleted threading.thread
in the server.py
well the code is a bit weird because you take input from stdin from multiple threads and then send that to all clients from each thread
and it still works
not sure what you're trying to do though
just trying to write a random message in the server.py
and it will print the message i wrote
in the client.py
and make it multiple times
you probably just want to take input in one place. if you connect with two clients it'll likely send to all clients twice
i'm about to run so i can't do a code review at the moment sorry :X
np
@tall olive ok i'm back, i was busy earlier, so could you explain to me what
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Does, and how i can reproduce the error
OSError: [Errno 98] Address already in use
To see if it's a problem i should deal with with that solution?
Possibly ping me when you can reply, in case i don't read the message..
@undone gust start your server, ctrl-c, try to start your server again
probably your threads hanging around
i know that sometimes it's used to exit a program (i saw it in ngrok) but it does nothing
try ctrl-c multiple times
ctrl-z does nothing as well
you're running this in a terminal?
yes
that's very surprising
ahah
wait
does ctrl-c or z cause a connection reset error?
because i have an except for those
to make it keep running
ctrl-c should raise KeyboardInterrupt and ctrl-z sends TSTP signal which i don't see anything in your code would catch and ignore either
and if not clients are connected you shouldn't have any threads spun up
oh yeah i heard of keyboard interrupt
also i can't replicate with the code you provided earlier. both work find
i was about to add an except for it but havent yet
how do you stop your server when you're testing?
by running it in terminal i mean i search the file and open it with python
@tall olive i either close it with the x or have the client send the server off command i added
but it's the same so mostly the x
the server off command is for when i deploy this little troll
what os are you on
i mean i opened the file, want me to open it from cmd?
like i searched it and clicked
if you're just running it maybe it doesn't use those control chars. i honestly don't know windows well enough
if you just close with the x and relaunch does it work?
probably not an issue for you then. maybe windows doesn't get the socket stuck in timewait
i opened it in cmd
and i did that
and it still did nothing
wait socket stuck in timewaiti? i think ive seen a similar error before
probably a different between windows and linux then. no need to add it if you're not experiencing the issue
like on my code
@tall olive i think ill still add it just in case, or just cause, so that little bit handles that error?
yeah
cant you just do except KeyboardInterrupt?
you can, and then cleanly close the socket
but if the process gets killed more aggressively you might still have the socket in a bad state
oh so that's "best practice"?
usually it clears after a couple mins but that option lets you rebind to the same address/port
should i add it like right after i do server.bind?
like where i "set up" things
or is there a preferred part of the code
oh yeah i still have one bug that bugs me a lot @tall olive
i have an exception for connection reset, where the user uses the x to close the client
but for some reason it doesnt work, it did before i added a lot of changesbut not any more
oh actually jk it doesnt do it anymore, insead of going in an infinite loop now it just throws an error and crashes the program
oh ok i just fixed it
sorry for the ping and.. the spam text. thanks a lot lot lot for all the help!!
no worries
i imagine the infinite loop is not accounting for recv returning an empty string when the client goes away
that's a super common bug people make
@undone gust
though actually looks like you account for that 
oh wait no, you account for it in get_msg
i imagine the infinite loop is not accounting for recv returning an empty string when the client goes away
@tall olive yeah that was the problem
but not in handle_client
if len(msg) is the same as if msg
oh yeah oops that's what i did
actually i'm having bad memory, what i did is:
if not msg: execute all the command checks etc
fuck i fucked up again
what i MEANT
is if not msg break
brain go brr
if not msg:
break
if msg == SHUT_OFF:
print(f"User {addr} has shut off {socket.gethostname()}, host PC.")
connected = False
elif msg == DISCONNECT:
print(f"User {addr} has disconnected from Server {ADDR}; listening for new connections.")
break
elif msg == SERVER_OFF:
print(f"User {addr} has shut off Server {ADDR}.")
for i in range(3, -1, -1):
sleep(1)
print(f"Shutting off in {i} seconds.")
quit()
elif msg.strip():
print(f"{nick}: '{msg}'")
that's what i do
haha
with all those stutters and alzheimer and fuck ups i'm making myself look stupid 
gary do you know what rotmg is?
oh yeah but this was a stupid error, but not beating myself up because this is more like about writing, since i had fixed it before the fuck ups
yeah realm of the mad god
i played it a very long time ago
ay guys
nothing much, u?
it's nice
i went to the ice cream shop and they brought back my favorite kind :0
they have LINDOR ICE CREAM
sorry i turned dm's off in this server because i get hassled a bit
like they make it themselves
oh you do?
didn't think this were a problem in a programming discord lolll
i just wanted to ask, how can i make if a client disconnects, it just instantly goes to attempt reconnect again?
i mean, if the server is closed
ya
oh idk about that
just because it's not like server.listen()
@tall olive can handle this one i think
this is actually an interesting question
i might add this to my own code
it just tries to reconnect until the server is started again
i literally have no ideas
maybe you can do while connected false client.connect(server) ?
that's just pseudo code
generally you don't want a client to reconnect as fast as possible or you can overwhelm the server if a lot of clients all try to reconnect at the same time
it's called thundering herd
sounds reasonable
but for small projects with like 1-2 clients max can you possibly do that?
i mean you can
but you probably want some amount of sleep so you don't just spin up your cpu if the server is down
i just made a random loop that keeps connecting
in my case i'll hide the server in a pc and i want to be able to connect to it with the client from wherever (i'm gonna be using ngrok cause i dont know any other way) and that feature would be useful
looking at cmd and other terminal servers and finally reading all of my own connection dc etc messages makes me feel like a badass 
i want to do something like that:
if connected:
messages()
even though it's just nerd shit for most people
lmao
maybe while connected would be better, depending on your use
share it here
did you crash yor pc
please share it, so we can learn ๐
i need to fix it
the other day i was testing my server with my brother via ngrok(tech lead at a company and he like 99% uses python), and the asshole started "ddosing me"
i had no lenght limit
he sent 3k long messages and spammed it
and my ram was at fucking 100% and cpou at 80%
just pull the ethernet cable...
good thinking ๐
also for your program, if you want to follow "best practice", add an if __name__"=="main" block
oh yeah i saw my brother do that when he looked at my code
@quick knoll why though?
like he explained it so "it activates if you run it like <file>.py"
but how else can you activate it
it just lets you control what happens when your run it vs use it as a library
usually you don't wanna spin up something that blocks the main thread on import
perfect ๐
i was surprised that no one ever mentioned the option of saving files as .pyw in any tutorials
i had to find it since i need to do that
yeah i know
but i need it to run in the background
so it cant be seen
also you can run them wherever you want as long as you install python (in this case 3)
like not as a tab
you can start multiple python processes at once
so it runs and does what it has to do but you cant see it there
@quick knoll ill get to the point: i want it to run in the background because this is a server i made to shut off my brother's pc, so if it doesnt run in the background he can just see a terminal open or he can alt tab and see it, which makes it useless

yeah but why would he if he doesnt know its running
like you dont randomly do that when you start your pc
thats true
besides he's an idiot he knows nothing about coding so he wouldnt know how to do that
i have 2 brothers btw, one is this idiot and the other is the one i mentioned earlier
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP_address = "1.1.1.1.1.1.1"
Port = 8888
# Always try to reconnect at the first try
def connect():
try:
server.connect((IP_address, Port))
except:
connect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
connect()
connect()
messages()
and this doesn't work
;//
also dont you have to give it a format to decode in?
i dont think you can reference connect() inside of connect()
so how can i make it to repeat?
you can
@ember ledge continue
it's prolly also just better
i think continue is better practice than that
but you may run into an recussion error
but you need to wrap it in a loop
but you may run into an recussion error
@quick knoll what's that
yeah cause you need to wrap the try statement in a while true loop for example
well, a loop for sure, the true is just good practice too
def loop():
return loop()
that's an infinite loop
no that will fail
i just need it to loop until it connects successfully
how will it fail if it keeps running
because python does not allow for infinite recursion
let me try this connect thing
i'll give it a shot
but not in actual pycarm cause creating a file is a hassle
def connect(addr):
while True:
try:
server.connect(addr)
break
except (whatever error arises when you cant connect):
continue
the only problem is i dont know what error (that you can call) arises
apart from that this should work
ill try
yeah but you need to know that error
ik
i'm scouring google rn
please add some timeout in the except
otherwise on every error you will be spamming that connect again
first of all, i've already heard of timeout and i'm actually very interested in finding out how it works because google didn't help me, second of all, well it spams up until you connect, which is bad for mem usage i guess but good if you REALLY want to connect again as soon as possible
so how do you use timeout? i actually need this for a feature i want to add on my code
no that's not the thing
timeout literally stops the code from running after some time
time.sleep() still loops infinetly
just slower
so because you are just running one loop you can use time.sleep. It may not be the best of ideas generally but to get started its fine
oh and just putting some 0.2 seconds is sufficient
but instead of failing maybe 100-500 times per second it now fails just 5 times
(if it fails)
i was interested in the actual socket.timeout() because i have a feature to shut down the host pc and i'd like to be able to give the host 5 seconds before it shuts down in which if he inputs anything he stops it from happening
you cant use input
inputimeout sucks too
and idk how to use socket.timeout() but that seems to be the best one
@quick knoll plez halp
the socket.timeout is useful for breaking out of some blocking operation like recv()
๐
time sleep for the progamm you are building is sufficient
because you arent doing anything if you are not connected, right?
so you might as well block the main thread
yeah for his program but not for mine
if you just use sleep and input it doesnt matter because input blocks the program
you have a server
yeah, but you want to wait on the main thread for any new clients
what?
i need to be able to wait for input for 5 seconds and if the 5 seconds pass without input do something and if i get input do something else
ahh
so that i have (for example) 5 seconds to stop from shutting down "my" pc
more like the server host pc
so you already have established the socket
yeah
then you can use socket.timeout
for input()?
because you are just using the socket operations
no i want the input to come from the server
not from the client
for once
like normal terminal input
hmm
see this is a real pickle
i tried inputimeout
but to no avail
it's a library btw
first: what do you want to do with the input?
if i get any input at all, even just a blank string (so basically if you press enter) i want to stop an operation
and if i get nothing (if the timeout turns off) i want to do something
in this case you have 5 seconds to cancel the command to shut off your pc
the server host pc, actually
ffs my mind gonna blow up, it is so hard to make a client always reconnect to the server
XD
yeahh the most mundane things take the most
so input() is blocking
so there are ways according to so
oh fuck yeah
but no guarantees ๐
def connect():
try:
server.connect((IP_address, Port))
messages()
except:
connect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
connect()
connect()
right after messages(), except
it just spams me errors
instead of going to connect()
which error?
doesn't show me
File "C:/Users/Laurynas/Desktop/project/client.py", line 16 in connect
...
except is too broad
lmao
what is line 16?
connect()
ya
it's when you call it
why not use while true and continue T^T
and yeah you just keep opening more functions before closing them i think
and if that's the case its very bad
can you print do print("reconnecting") in the except block
before connect()?
yes
k
wait
it is the same
Fatal Python error: Cannot recover from stack overflow.
Python runtime state: initialized
Current thread 0x000149e4 (most recent call first):
ah wait
it is the same
didn't print that text
yeah well the print is just to see if it gets there
uhm it does...
def connect():
try:
server.connect((HOST, PORT))
messages()
except:
print('here ... ')
connect()
or at least now im getting :
ConnectionRefusedError: [Errno 111] Connection refused
yeahh a sleep time would be nice i guess
maybe even a count to make it stop after tot tries
very nice idea
can you share your entire file?
import socket
import time
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect():
try:
server.connect((HOST, PORT))
messages()
except ConnectionRefusedError:
print("reconnecting, please wait...")
time.sleep(0.1)
connect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
connect()
connect()
# Python program to implement client side of chat room.
import socket
import time
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = socket.gethostname()
PORT = 8888
def connect():
try:
server.connect((HOST, PORT))
messages()
except ConnectionRefusedError:
time.sleep(0.1)
connect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
connect()
connect()
uh
why do you reference messages() before you declare it
you cant do that right? not even when defining i think
File "C:/Users/Laurynas/Desktop/project/client.py", line 13, in connect
server.connect((HOST, PORT))
OSError: [WinError 10056] Jungimosi uลพklausa atlikta jau prisijungusiame lizde
@ember ledge can you do a print(HOST) under the host assignment?
def connect(addr: tuple):
count = 0
while True:
try:
server.connect(addr)
messages()
except ConnectionRefusedError:
print(f"failed connection time {count}")
count += 1
if count < max_count:
time.sleep(0.2)
continue
File "C:/Users/Laurynas/Desktop/project/client.py", line 13, in connect
server.connect((HOST, PORT))
OSError: [WinError 10056] Jungimosi uลพklausa atlikta jau prisijungusiame lizde
@ember ledge please translate that
that's just uto not have it infintely loop
does not work..
ohh yeah
socket.gethostbyname(socket.gethostname())
YIKES
how did we miss that for all this time
@ember ledge you have to do socket.gethostbyname(socket.gethostname()) instead
gethostname gets your pc's "name", gethostbyname gets your lan ip based on your pc name
that will return your local ip address
exactly
its the same
it's not
"request is already done"
oh the error
are you killing the python process correct?
yeah
oh yeah you gotta do conn.close()
where
i've done it
keeps reconnecting
perfect
you had some "zombie" socket connection in the server
that was connected but was essentially dead
i mean, if you start the server, then the client, close the server, and the client keeps reconnecting
until the server is opened again
no
i think we need a new socket
2 sockets i guess
because the current one is already done
"request is done"
add server.settimeout(0.2) after server.connect((HOST, PORT))
or any other number that works for you
well you need to close that conn on client side too to connect again i think
i think
that will raise an error after the time on server.recv(), because you may not be closing that server correct
because there is still a client on you server
if there's no server.settimeout
it works well
but it can't reconnect again
when server is closed
i just want the client to keep reconnecting
I know
lol
how does your server look like?
import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = socket.gethostbyname(socket.gethostname())
server.bind((host, 8888))
server.listen(2)
client_sockets = []
def sendallclients(message):
for x in client_sockets:
try:
x.send(message)
except:
client_sockets.remove(conn)
def sendd():
while True:
message = input(">>> ").encode()
if not client_sockets:
print("There are no clients!")
else:
sendallclients(message)
while True:
conn, addr = server.accept()
client_sockets.append(conn)
print(str(addr[0]) + " has connected succesfully!")
threading.Thread(target=sendd).start()
conn.close()
server.close()
what does the listen argument even do
Jk that's just for the backlog iirc
also hi natycat
yeah no it's not iirc
i manage to get 2 conns (or more) if i set it to 1
hey guys let's see how many clients it takes for my laptop to explode
like concurrent clients
you can leave that out completely
as you are spawning threads for the individual clients
Wait each client is getting a new thread but then you are using each thread to send to every client?
Doesn't make sense
wait no im talking about my own code
not his
sorry maybe you were talking to him and not me
Yes but I am talking about his
ohh
can you call input from any thread=
You probably want a client to be giving out the messages to other clients
like an observer pattern?
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP_address = "1.1.1.1.1.1.1"
Port = 8888
# Always try to reconnect at the first try
def connect():
try:
server.connect((IP_address, Port))
except:
connect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
connect()
connect()
messages()
i want to do something like this lol
but it'll spam connections
can't do a single one
yes, because you removed the sleep ๐
Lmao I'm so sure
dont think so
Your ISP will get you a new ip
imagine if websites logged their user's ips
import socket
import time
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = socket.gethostbyname(socket.gethostname())
PORT = 8888
def connect():
try:
server.connect((HOST, PORT))
messages()
except ConnectionRefusedError:
print("reconnecting, please wait...")
time.sleep(0.1)
connect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
connect()
connect()
server.close()
k current code
i get "request is done"
@undone gust they do wdym
of course they do, how do you think cookies work etc ๐
ffs im stuck almost 4-5 hours
also how do you think VPNs enable you to be in a different country
of course they do, how do you think cookies work etc ๐
T^T
also how do you think VPNs enable you to be in a different country
@quick knoll by using their ip but i didnt think they saved them
like logs
makes sense though
@ember ledge , your server implementation results in the client getting reset on connection
tbh, i think i need a new socket
nonono
you probably need to read https://realpython.com/python-sockets/#echo-server
ohh that drawing
i've read
i just watched a yt video for the basics then used google and stack overflow to learn everything else related to it
there's ton of documentation online nowadays
ill give those a read later
might be useful
XDD
it do be like that sometimes
@ember ledge did you implement their ideas and try them yourself once?
and then iterate on that? ๐
okay
but just i cant make a simple reconnect function
because you are trying two new things at once
the reconnect is fine, the timing will take some work, but you are on the right way there
the server gives me a headache tho
Reconnects really aren't as simple as your might think
@ember ledge if i remember to and find the time to i'll try it out and work on it tonight, ping me in like 14 hours or some after i wake up and ask me if i did it so i'll share the code with you
alright
Why do you want to do such a low level socket anyway
what are low level sockets
what you are doing
^
what do you have in mind?
For what he's doing something like socketio would be better for this
because its really difficult already, and even "higher level" abstraction will probably just confuse more.
puuh
what's socketio
Low level sockets are much harder than higher level abstractions, they remove alot of the nitty gritty
It's a module that makes a event based socket system which is a bit higher than pure sockets
I just googled that, looks better, I was scared you were pointing them to async stuff
Nah, altho I mostly work with asyncio, stuff gets alot more wild
async stuff?
Dw about it
๐
Not when you're doing it
not in python
Not when you're doing it
@gloomy root


