#networks

1 messages ยท Page 17 of 1

ember ledge
#

self._header_size is an int, 64

tall olive
#

Did you bind?

#

@ember ledge

ember ledge
#

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?

vernal surge
#

Yes

#

You have to bind to an interface regardless of the protocol

ember ledge
#

ok

tall olive
#

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

ember ledge
#

that is usually what happens

tall olive
#

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

ember ledge
#

its weird, because it works fine on the server

tall olive
#

seems to confirm you either need to bind or send first

#

are you binding on the server?

ember ledge
#

huh

#

yeah

#

i wonder why it works fine using TCP sockets

tall olive
#

tcp gives you a port on bind or connect

#

udp gives you a port on bind or send, not recv

ember ledge
#

oh ok

tall olive
#

if you send something first you'd get a port

ember ledge
#

hmm, so should I just send a dummy "connected" packet or something?

tall olive
#

well it's a weird model to have a client that receives unsolicited packets

ember ledge
#

im currently using both a TCP and UDP socket

#

so the TCP socket will connect, then they will both listen on seperate threads

tall olive
#

how do you know how to get the packet to the udp socket?

#

what port are you sending to?

ember ledge
#

same port

tall olive
#

no

ember ledge
#

im pretty sure you can use TCP and UDP sockets on the same port

#

im probably going about this a very incorrect way lol

tall olive
#

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

ember ledge
#

would there be a way to tell what port the TCP socket has bound to?

tall olive
#

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

ember ledge
#

ok

tall olive
#

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

ember ledge
#

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

tall olive
#

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

ember ledge
#

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)

tall olive
#

but you could do something like

sock.bind(("0.0.0.0", 0))
_, port = sock.getsockname()
ember ledge
#

or, I guess just do socket_udp.bind(socket_tcp.getsockname())

tall olive
#

and communicate that back to the server

ember ledge
#

what would 0.0.0.0:0 be?

tall olive
#

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?

ember ledge
#

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?

tall olive
#

right, so there's nothing to say that tcp port isn't in use for udp by another application

ember ledge
#

huh

tall olive
#

you can't just assume an ephemeral port is not going to be in use

ember ledge
#

fair enough

#

is there anyway I can get one that definately isnt?

#

or will it have to be a static port?

tall olive
#

bind to 0

ember ledge
#

ok

tall olive
#

that will get you a port that's not in use

ember ledge
#

by both protocols?

tall olive
#

no

ember ledge
#

oh

tall olive
#

i'm not sure there's any atomic way to ask for a port that's not in use by both protocols

ember ledge
#

oh

#

right, well I guess ill have to change my server framework then

tall olive
#

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

ember ledge
#

how would the server be able to identify who the UDP packet is from?

#

should I make UUIDs or something?

tall olive
#

send it over the tcp connection

ember ledge
#

oh ok

#

good idea

tall olive
#

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

ember ledge
#

yeah

tall olive
#

gotta run to get some lunch. good luck!

ember ledge
#

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)

strong laurel
#

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

ember ledge
#

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

tall olive
#

what does the code look like for the send?

ember ledge
#

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)
tall olive
#

do you have more of the traceback and the connection and recv code?

ember ledge
#
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)
tall olive
#

is the recv happening in the socket thread?

ember ledge
#

yup

tall olive
#

mind sharing that as well?

ember ledge
#

sure

#

1 min

#

should I just send the entire file? the socket thread is larger than 2000 characters :P

tall olive
#

!paste

errant bayBOT
#

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.

tall olive
#

might be worth just sharing the whole thing

ember ledge
#

ok

#

note that the majority of the code is experimental and ill refine it once I have something working

tall olive
#

no worries ๐Ÿ™‚

strong laurel
#

anyone think they could help me with this project im working on

#

i have to implement a method using two other classes

tall olive
#

@ember ledge

        if enable_udp:
            self._socket_udp = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM
            )
#

notice anything wrong there?

ember ledge
#

FUCK

#

i must have changed it to TCP to test something and forgot to change it back

#

sorry for wasting your time ๐Ÿ˜…

tall olive
#

no worries

#

sometimes you just need fresh eyes

ember ledge
#

true

#

thanks for all your help @tall olive ๐Ÿ™‚

tall olive
#

wanna test it real quick just to confirm that was def it?

ember ledge
#

yup

#

seems to be working now ๐Ÿ‘

tall olive
#

awesome

#

back to work ๐Ÿคฃ

ember ledge
#

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

tall olive
#

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

ember ledge
#

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

tall olive
#

hmm, that's not my experience testing locally thoncque

ember ledge
#

btw, it works fine running on localhost

#

just not over global connections

tall olive
#

one sec, lemme open a port on a server so i can test something

ember ledge
#

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

tall olive
#

hmm, i just tested this across servers and it worked as expected

ember ledge
#

any idea what could be happening?

tall olive
#
>>> 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))
ember ledge
#

ill try running that

tall olive
#

is the code the same as what you shared earlier?

ember ledge
#

slightly different, ill make a pastebin

#

!paste

errant bayBOT
#

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.

ember ledge
#

btw, that code works in the python shell

#

so its something up with my code

tall olive
#

that's good to confirm i'm not crazy ๐Ÿ˜„

ember ledge
#

haha yeah

tall olive
#

though weird that it'd work local thonking

ember ledge
#

ikr

tall olive
#

@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

ember ledge
#

yeah, that is just the class that the user would inherit from

#

i can send you the example im using to test?

tall olive
#

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

ember ledge
#

wait why does it think it is a ruby file

tall olive
#

jank.networking blobrofl

ember ledge
#

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

tall olive
#

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

ember ledge
#

im pretty sure, cos the server isnt receiving the Clients controls

tall olive
#

is this running on a linux host?

ember ledge
#

nope

#

windows

tall olive
#

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

ember ledge
#

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

tall olive
#

i only asked because it's a mistake we all make a thousand times

ember ledge
#

it is the minecraft port, so maybe something was trying to connect

tall olive
#

ah, interesting

ember ledge
#

(its the only port i have forwarded)

tall olive
#

always a good exercise to have your understanding of a technology challenged

ember ledge
#

yeah, thanks for your help @tall olive

#

(again)

tall olive
#

no problem. looks like a fun project

#

and i'm sure you're learning a lot of cool stuff ๐Ÿ™‚

ember ledge
#

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

tall olive
#

nice. it's a super useful part of the stack to learn. demystifies how much of the internet technologies work

ember ledge
#

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

tall olive
#

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

ember ledge
#

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 >:)

tall olive
#

๐Ÿ™‚

#

alright, gonna get some sleep

ember ledge
#

gn, and thanks again for all your help! @tall olive

modern oriole
#

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

empty solstice
#

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

modern oriole
#

I see

empty solstice
#

yep

thorny locust
#

is there a way to get requests to use the windows certificate store?

#

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

fathom condor
#

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

empty solstice
#

@fathom condor do you mean that your problem is that you are not able to find the minecraft dir??

#

or something else

fathom condor
#

I need to find usercache.json

#

here is my code

empty solstice
#

ohh

fathom condor
#
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'

empty solstice
#

so it is that minecraft dir na??

fathom condor
#

no

empty solstice
#

ohh I get it

fathom condor
#

its a pebblehost server

empty solstice
#

you are not able to find that userchache thing

fathom condor
#

i think thats what the error means

#

idk

empty solstice
#

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

fathom condor
#

@empty solstice

empty solstice
#

yes

fathom condor
#

I have the full adress for the file i need

empty solstice
#

gg

fathom condor
#

how do I use pickle for that?

empty solstice
#

no not for that

fathom condor
#

?

empty solstice
#

for sending or reading something in the file

fathom condor
#

oh

empty solstice
#

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

vernal surge
#

Why ftp? It's a fairly broken protocol

fathom condor
#

what should I use

#

I just need to read usercache.json

#

@vernal surge

vernal surge
#

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

thorn stratus
#

SFTP works good as well

tall olive
#

@fathom condor can you share a full traceback

#

also the rest of your code. are you calling usercache multple times?

pure mica
#

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?

gloomy root
#

Whats your full code

tall olive
#

@fathom condor I bet you're calling usercache multiple times and usercache is closing the ftp connection after the first time

pure mica
#
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

thorn stratus
#

Use a time out

#

and make your own try except

pure mica
#

Use a time out
@thorn stratus could you pls send an example

thorn stratus
#

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

pure mica
#

Thanks

ember ledge
#

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

wraith grove
#

does the client work on the machine running the server

ember ledge
#

yes

wraith grove
#

then its purely a network issue

#

did you port forward

ember ledge
#

ya

wraith grove
#

show me the port forward rule

ember ledge
#

wait a min

undone gust
#

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?

tall olive
#

@ember ledge is your friend connecting to 192.168.0.102?

#

that's an internal IP on your network

undone gust
#

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

tall olive
#

@undone gust would need to see code

undone gust
#

ok

#

it's..

#

too big

#

over 2k chars

errant bayBOT
#

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:

https://paste.pythondiscord.com

tall olive
#

yeah, use a pastebin like the bot suggested

undone gust
#

this pastebin looks cool af sunglassesvery3dcool

#

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

ember ledge
#

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 that 192.168.0.102 on the server.py?

#

i just put my public ip in the client

#

and it still works

tall olive
#

@ember ledge yea, you need to kick your local ip on the server

#

your router will forward to that ip

ember ledge
#

bruh im so confused

undone gust
#

Mood.

tall olive
#

@undone gust

            thread = threading.Thread(target=handle_client(conn, addr))
#

you're calling the function

#

so it blocks there

undone gust
#

wdym

tall olive
#

that needs to be

            thread = threading.Thread(target=handle_client, args=(conn, addr))
undone gust
#

oh god i want to kick myself, in the tutorial i was watching they did like you told me to

tall olive
#

you're calling handle_client so it spins that function up in the local thread

undone gust
#

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

tall olive
#

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

undone gust
#

wdym reuse the port

tall olive
#

that'l l get rid of

OSError: [Errno 98] Address already in use
#

if you try to start it after the server crashing

undone gust
#

oh like if i start the server program again without closing it first?

tall olive
#

yeah

undone gust
#

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

tall olive
#

anyways imagine this

            handler = handle_client(conn, addr)
            thread = threading.Thread(target=handler)
#

can you see what that doesn't work?

undone gust
#

yeah because it has no arguments

ember ledge
#

yo guyss

tall olive
#

handle_client will loop forever

#

and never create the thread

ember ledge
#

and it worked

#

lol ty so much

tall olive
#

@ember ledge no problem ๐Ÿ™‚

undone gust
#

holy shit gary

#

i love you so much

tall olive
#

@undone gust it's not about the args, that's the same as what you were doing

undone gust
#

it worked

#

i have 2 clients connected and working

tall olive
#

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

undone gust
#

oh so targert=handle_client(conn, addr) creates like a variable of handle_client but without actually providing stuff?

tall olive
#

then the thread started up and runs your function inside the thread

undone gust
#

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

tall olive
#

right

undone gust
#

argh thank you so much man

#

โค๏ธ โค๏ธ โค๏ธ โค๏ธ

tall olive
#

it's trying to pass the result of your function (which would be None) to the target of thread creation

undone gust
#

ohhh

tall olive
#

but it just blocks because it the while loop

undone gust
#

and it worked because meanwhile its still running it?

tall olive
#

right

undone gust
#

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

tall olive
#

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

undone gust
#

yeah thats ok

#

will do

#

good samaritan :))

undone gust
#

Ook im back :)

#

With worse writing and slower than before due to mobile

ember ledge
#

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

undone gust
#

@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

ember ledge
#

nope

#

got a syntax error

undone gust
#

What's the server code?

#

Or at least the messages function +when you start the thread

ember ledge
#
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()
undone gust
#

Try doing threading.thread(target=(sendd), args=()).start()

#

And then tell me what happens

tall olive
#
while True:
    threading.Thread(target=messages).start()
#

you're just starting an infinite number of threads in a tight loop

undone gust
#

Also shouldn't yoi assign it

ember ledge
#

so what do i need to do?

#

@tall olive

undone gust
#

Like test = threading.thread etx

tall olive
#

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

undone gust
#

Wait why do you create a thread on the client

tall olive
#

also that ^ heh

undone gust
#

Yay

ember ledge
#

i need to receive every message i send on server

tall olive
#

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()

ember ledge
#

oh

#

it works

tall olive
#
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()
ember ledge
#

ya

#

what can i change?

tall olive
#

what do you mean? is something wrong?

#

or are you asking for a general code review?

ember ledge
#

ya

#

general code review

#

oh, i literally deleted threading.thread

tall olive
#

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

ember ledge
#

and it still works

tall olive
#

not sure what you're trying to do though

ember ledge
#

just trying to write a random message in the server.py

#

and it will print the message i wrote

#

and make it multiple times

tall olive
#

you probably just want to take input in one place. if you connect with two clients it'll likely send to all clients twice

ember ledge
#

what can i change?

#

im literally a beginner here lol

tall olive
#

i'm about to run so i can't do a code review at the moment sorry :X

ember ledge
#

np

undone gust
#

@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..

tall olive
#

@undone gust start your server, ctrl-c, try to start your server again

undone gust
#

ok let's see:

#

i pressed ctrl-c and nothing happened

tall olive
#

probably your threads hanging around

undone gust
#

i know that sometimes it's used to exit a program (i saw it in ngrok) but it does nothing

tall olive
#

try ctrl-c multiple times

undone gust
#

ok

#

i pressed it like 30 times and nothing happened

tall olive
#

ctrl-z

#

then kill %1

undone gust
#

ctrl-z does nothing as well

tall olive
#

you're running this in a terminal?

undone gust
#

yeah

#

want me to run it in pycharm?

tall olive
#

nah

#

do you have a client connected?

undone gust
#

not yet no

#

should i connect one?

tall olive
#

no, just curious

#

so your server continues to run and ignores ctrl-z?

undone gust
#

yes

tall olive
#

that's very surprising

undone gust
#

ahah

#

wait

#

does ctrl-c or z cause a connection reset error?

#

because i have an except for those

#

to make it keep running

tall olive
#

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

undone gust
#

oh yeah i heard of keyboard interrupt

tall olive
#

also i can't replicate with the code you provided earlier. both work find

undone gust
#

i was about to add an except for it but havent yet

tall olive
#

how do you stop your server when you're testing?

undone gust
#

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

tall olive
#

what os are you on

undone gust
#

windows 10

#

dont shame me

tall olive
#

i won't

#

just curious

undone gust
#

ill get linux in a couple days >.>

#

like on an usb

tall olive
#

i'm not super familiar with windows

#

you're running in cmd?

undone gust
#

i mean i opened the file, want me to open it from cmd?

#

like i searched it and clicked

tall olive
#

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?

undone gust
#

yeah

#

i'm tryna open it from cmd now

tall olive
#

probably not an issue for you then. maybe windows doesn't get the socket stuck in timewait

undone gust
#

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

tall olive
#

probably a different between windows and linux then. no need to add it if you're not experiencing the issue

undone gust
#

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?

tall olive
#

yeah

undone gust
#

cant you just do except KeyboardInterrupt?

tall olive
#

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

undone gust
#

oh so that's "best practice"?

tall olive
#

usually it clears after a couple mins but that option lets you rebind to the same address/port

undone gust
#

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!!

tall olive
#

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 thoncque

#

oh wait no, you account for it in get_msg

undone gust
#

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

tall olive
#

but not in handle_client

undone gust
#

yeah exactly!

#

i added if len(msg) to counter that

#

ah ah! i beat you in time!

#

xD

tall olive
#

if len(msg) is the same as if msg

undone gust
#

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

tall olive
#

haha

undone gust
#

with all those stutters and alzheimer and fuck ups i'm making myself look stupid monkaS

#

gary do you know what rotmg is?

tall olive
#

network programming is a bit complex so don't beat yourself up

#

realm of the mad god?

undone gust
#

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

tall olive
#

i played it a very long time ago

undone gust
#

ok maybe lets bring this to dms

#

jk i cant dm you

ember ledge
#

ay guys

undone gust
#

ayyy

#

wassup

ember ledge
#

nothing much, u?

undone gust
#

it's nice

#

i went to the ice cream shop and they brought back my favorite kind :0

#

they have LINDOR ICE CREAM

tall olive
#

sorry i turned dm's off in this server because i get hassled a bit

undone gust
#

like they make it themselves

#

oh you do?

#

didn't think this were a problem in a programming discord lolll

ember ledge
#

i just wanted to ask, how can i make if a client disconnects, it just instantly goes to attempt reconnect again?

undone gust
#

oh i know!

#

it depends on how you close the client

ember ledge
#

i mean, if the server is closed

undone gust
#

if you do conn.close or if you just close it with the x

#

oh the server?

ember ledge
#

ya

undone gust
#

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

ember ledge
#

it just tries to reconnect until the server is started again

#

i literally have no ideas

undone gust
#

maybe you can do while connected false client.connect(server) ?

#

that's just pseudo code

tall olive
#

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

undone gust
#

sounds reasonable

tall olive
#

you'd wanna look into something called exponential backoff

#

with random jitter

undone gust
#

but for small projects with like 1-2 clients max can you possibly do that?

tall olive
#

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

ember ledge
#

i just made a random loop that keeps connecting

undone gust
#

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

ember ledge
#

but it'll spam: ip just connected!

#

and etc.

undone gust
#

looking at cmd and other terminal servers and finally reading all of my own connection dc etc messages makes me feel like a badass sunglassesvery3dcool

ember ledge
#

i want to do something like that:
if connected:
messages()

undone gust
#

even though it's just nerd shit for most people

ember ledge
#

lmao

undone gust
#

maybe while connected would be better, depending on your use

ember ledge
#

bruh wtf

#

i just did a random code

#

and it works well

undone gust
#

share it here

ember ledge
#

oh no

#

wait

undone gust
#

did you crash yor pc

ember ledge
#

almost

#

XDDD

quick knoll
#

please share it, so we can learn ๐Ÿ™‚

ember ledge
#

i need to fix it

undone gust
#

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%

quick knoll
#

just pull the ethernet cable...

undone gust
#

cause i was on a shitty laptop

#

nah i just closed the program and added a limit

quick knoll
#

good thinking ๐Ÿ™‚

#

also for your program, if you want to follow "best practice", add an if __name__"=="main" block

undone gust
#

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

quick knoll
#

thats correct

#

try print(__name__)

tall olive
#

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

undone gust
#

oh

#

ok i'll do that then

#

boom done

quick knoll
#

perfect ๐Ÿ™‚

undone gust
#

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

quick knoll
#

why ?

#

you can run python(.py) files w/ win 10

undone gust
#

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)

quick knoll
#

that shouldnt be an issue either way

#

what do you mean background?

undone gust
#

like not as a tab

quick knoll
#

you can start multiple python processes at once

undone gust
#

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

quick knoll
#

he can just ps | grep python + kill {PYTHON ID}

#

๐Ÿ˜‰

undone gust
#

yeah but why would he if he doesnt know its running

#

like you dont randomly do that when you start your pc

quick knoll
#

thats true

undone gust
#

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

ember ledge
#
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

#

;//

undone gust
#

can you even just do except?

#

i know pycharm hates it

#

it tells me it's too broad

ember ledge
#

im just coding in the original python IDE

#

XDDDDDD

#

lemme turn on the pycharm

undone gust
#

also dont you have to give it a format to decode in?

ember ledge
#

uh no

#

message() works well

undone gust
#

i dont think you can reference connect() inside of connect()

ember ledge
#

so how can i make it to repeat?

quick knoll
#

you can

undone gust
#

@ember ledge continue

#

it's prolly also just better

#

i think continue is better practice than that

quick knoll
#

but you may run into an recussion error

undone gust
#

but you need to wrap it in a loop

#

but you may run into an recussion error
@quick knoll what's that

ember ledge
#

lol

undone gust
#

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

quick knoll
#
def loop():
    return loop()
undone gust
#

that's an infinite loop

quick knoll
#

no that will fail

ember ledge
#

i just need it to loop until it connects successfully

undone gust
#

how will it fail if it keeps running

quick knoll
#

because python does not allow for infinite recursion

undone gust
#

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

ember ledge
#

ill try

undone gust
#

yeah but you need to know that error

ember ledge
#

ik

undone gust
#

i'm scouring google rn

quick knoll
#

please add some timeout in the except

#

otherwise on every error you will be spamming that connect again

undone gust
#

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

ember ledge
#

time.sleep(5)

#

lol

undone gust
#

no that's not the thing

#

timeout literally stops the code from running after some time

#

time.sleep() still loops infinetly

#

just slower

quick knoll
#

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)

undone gust
#

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

quick knoll
#

the socket.timeout is useful for breaking out of some blocking operation like recv()

undone gust
#

yeah i read that it's only for socket operations

#

and that was a real goddamn bummer

quick knoll
#

๐Ÿ˜„

undone gust
#

so there's no way to adapt it?

#

or any other similar useful function??

quick knoll
#

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

undone gust
#

yeah for his program but not for mine

#

if you just use sleep and input it doesnt matter because input blocks the program

quick knoll
#

you have a server

undone gust
#

yeah i do

#

well a basic one

quick knoll
#

yeah, but you want to wait on the main thread for any new clients

undone gust
#

nonono

#

i'm trying to do a different thing

quick knoll
#

what?

undone gust
#

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

quick knoll
#

ahh

undone gust
#

so that i have (for example) 5 seconds to stop from shutting down "my" pc

#

more like the server host pc

quick knoll
#

so you already have established the socket

undone gust
#

yeah

quick knoll
#

then you can use socket.timeout

undone gust
#

for input()?

quick knoll
#

because you are just using the socket operations

undone gust
#

no i want the input to come from the server

#

not from the client

#

for once

#

like normal terminal input

quick knoll
#

hmm

undone gust
#

see this is a real pickle

#

i tried inputimeout

#

but to no avail

#

it's a library btw

quick knoll
#

first: what do you want to do with the input?

undone gust
#

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

ember ledge
#

ffs my mind gonna blow up, it is so hard to make a client always reconnect to the server

#

XD

undone gust
#

yeahh the most mundane things take the most

quick knoll
#

so input() is blocking

undone gust
#

yeah

#

and i need to stop input after 5 seconds

quick knoll
#

so there are ways according to so

undone gust
#

oh fuck yeah

quick knoll
#

but no guarantees ๐Ÿ™‚

ember ledge
#
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()

quick knoll
#

which error?

ember ledge
#

doesn't show me

undone gust
#

yeah you have to specify what error you want to except

#

i think

ember ledge
#

File "C:/Users/Laurynas/Desktop/project/client.py", line 16 in connect
...

undone gust
#

except is too broad

ember ledge
#

lmao

quick knoll
#

what is line 16?

undone gust
#

connect()

ember ledge
#

ya

undone gust
#

it's when you call it

quick knoll
#

heh

#

its the recursion error I bet you

undone gust
#

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

quick knoll
#

can you print do print("reconnecting") in the except block

ember ledge
#

before connect()?

quick knoll
#

yes

ember ledge
#

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

undone gust
#

yeah well the print is just to see if it gets there

quick knoll
#

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
undone gust
#

oh ok you need to do except ConnectionRefusedError:

#

that's the error

quick knoll
#

no

#

the problem is that this error occurs really quickly... like 1000 times / second

undone gust
#

yeahh a sleep time would be nice i guess

#

maybe even a count to make it stop after tot tries

quick knoll
#

very nice idea

undone gust
#

thanks

#

i'll actually add that to my own client

ember ledge
#

my head is about to explode lol

#

it doesn't work for me

quick knoll
#

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()
ember ledge
#
# 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()
undone gust
#

uh

#

why do you reference messages() before you declare it

#

you cant do that right? not even when defining i think

quick knoll
#

you can do that

#

and even if you cannot, it doesnt matter, this isnt the problem

ember ledge
#

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

quick knoll
#

@ember ledge can you do a print(HOST) under the host assignment?

undone gust
#
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

ember ledge
#

it says that it is already completed

#

that request

#

in that host, port

quick knoll
#

because thats actually true

#

HOST = socket.gethostname()

ember ledge
#

i have done

#

it

quick knoll
#

does not work..

undone gust
#

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

quick knoll
#

that will return your local ip address

undone gust
#

exactly

ember ledge
#

its the same

undone gust
#

it's not

ember ledge
#

"request is already done"

undone gust
#

oh the error

quick knoll
#

are you killing the python process correct?

ember ledge
#

yeah

undone gust
#

oh yeah you gotta do conn.close()

ember ledge
#

where

undone gust
#

on the server

#

when you close the client

ember ledge
#

i've done it

quick knoll
#

uhm

#

can you close the server and just run the client code?

ember ledge
#

keeps reconnecting

quick knoll
#

perfect

#

you had some "zombie" socket connection in the server

#

that was connected but was essentially dead

ember ledge
#

but it wont reconnect again

#

when a server suddenly closes

quick knoll
#

uhm

#

you are starting the server, then the client, and then you restart the server?

ember ledge
#

i mean, if you start the server, then the client, close the server, and the client keeps reconnecting

#

until the server is opened again

quick knoll
#

does that work=

#

or not?

ember ledge
#

no

#

i think we need a new socket

#

2 sockets i guess

#

because the current one is already done

#

"request is done"

quick knoll
#

add server.settimeout(0.2) after server.connect((HOST, PORT))

#

or any other number that works for you

undone gust
#

well you need to close that conn on client side too to connect again i think

#

i think

quick knoll
#

that will raise an error after the time on server.recv(), because you may not be closing that server correct

ember ledge
#

server.settimout()

#

it instantly gives me a "request is already done"

quick knoll
#

because there is still a client on you server

ember ledge
#

if there's no server.settimeout

#

it works well

#

but it can't reconnect again

#

when server is closed

quick knoll
#

uhm

#

you mean when you reopen it?

ember ledge
#

i just want the client to keep reconnecting

quick knoll
#

I know

ember ledge
#

ya

#

but

undone gust
#

lol

quick knoll
#

how does your server look like?

ember ledge
#
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()
undone gust
#

what does the listen argument even do

thorn stratus
#

Jk that's just for the backlog iirc

undone gust
#

also hi natycat

thorn stratus
#

Was thinking it was for number of connections

#

Hi

ember ledge
#

ya

#

hi

undone gust
#

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

quick knoll
#

you can leave that out completely

#

as you are spawning threads for the individual clients

undone gust
#

yes

#

LOLL

#

each client gets a new thread

#

so i can read the msg at the "same time"

thorn stratus
#

Wait each client is getting a new thread but then you are using each thread to send to every client?

#

Doesn't make sense

undone gust
#

wait no im talking about my own code

#

not his

#

sorry maybe you were talking to him and not me

thorn stratus
#

Yes but I am talking about his

undone gust
#

ohh

quick knoll
#

can you call input from any thread=

thorn stratus
#

You probably want a client to be giving out the messages to other clients

quick knoll
#

like an observer pattern?

ember ledge
#
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

quick knoll
#

yes, because you removed the sleep ๐Ÿ˜„

ember ledge
#

can u send the whole code?

#

im literally so confused

undone gust
#

why do you use "1.1.1.1.1.1.1"

#

wtf is that

ember ledge
#

i just did it random lol

#

to hide my public ip

thorn stratus
#

Ipv6 leetmode

#

/s

undone gust
#

oh ok

#

i mean your public ip really isn't that secret

#

or important either i guess

ember ledge
#

meh

#

skids gonna ddos me or etc.

thorn stratus
#

Lmao I'm so sure

undone gust
#

dont think so

thorn stratus
#

Your ISP will get you a new ip

undone gust
#

imagine if websites logged their user's ips

ember ledge
#
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"

thorn stratus
#

@undone gust they do wdym

undone gust
#

oh raelly

quick knoll
#

of course they do, how do you think cookies work etc ๐Ÿ˜„

ember ledge
#

ffs im stuck almost 4-5 hours

quick knoll
#

also how do you think VPNs enable you to be in a different country

undone gust
#

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

quick knoll
#

@ember ledge , your server implementation results in the client getting reset on connection

ember ledge
#

tbh, i think i need a new socket

quick knoll
#

nonono

undone gust
#

ohh that drawing

ember ledge
#

i've read

undone gust
#

it's nice

#

i've read neither of those

quick knoll
undone gust
#

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

ember ledge
#

ffs, im gonna watch some yt videos about sockets

#

before sleep

undone gust
#

might be useful

ember ledge
#

XDD

undone gust
#

it do be like that sometimes

quick knoll
#

@ember ledge did you implement their ideas and try them yourself once?

#

and then iterate on that? ๐Ÿ™‚

ember ledge
#

i did multiple times

#

with my ideas

quick knoll
#

okay

ember ledge
#

but just i cant make a simple reconnect function

quick knoll
#

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

gloomy root
#

Reconnects really aren't as simple as your might think

undone gust
#

@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

ember ledge
#

alright

gloomy root
#

Why do you want to do such a low level socket anyway

undone gust
#

what are low level sockets

quick knoll
#

what you are doing

gloomy root
#

^

quick knoll
#

what do you have in mind?

gloomy root
#

For what he's doing something like socketio would be better for this

quick knoll
#

because its really difficult already, and even "higher level" abstraction will probably just confuse more.

#

puuh

undone gust
#

what's socketio

gloomy root
#

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

quick knoll
#

I just googled that, looks better, I was scared you were pointing them to async stuff

gloomy root
#

Nah, altho I mostly work with asyncio, stuff gets alot more wild

undone gust
#

async stuff?

quick knoll
#

dont!

#

listen to us!

gloomy root
#

Dw about it

quick knoll
#

๐Ÿ˜„

undone gust
#

isn't low level stuff higher performance

#

like C is a beast

#

absolute monster

gloomy root
#

Not when you're doing it

quick knoll
#

not in python

undone gust
#

Not when you're doing it
@gloomy root sad_peepo