G
G
GroMan_L2022-03-21 12:21:21
Python
GroMan_L, 2022-03-21 12:21:21

Adding arguments to a function with threading?

I am trying to make a chat on python socket and to send messages I am using threading.
Here is the code:

import socket, threading

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((socket.gethostbyname(socket.gethostname()), 5555))

def send(ip):
    message = input(': ')
    ip.send(message.encode('utf-8'))

server.listen(2)

if __name__ == '__main__':
    th = threading.Thread(target=send, kwargs=({'ip': conn}))
    while True:
        conn, adr = server.accept()

        data = conn.recv(2048)
        print(data.decode('utf-8'))
        th.run(conn)


On the line th = threading.Thread(target=send, kwargs=({'ip': conn})) gives an error:

Traceback (most recent call last):
File "D:\Python\Class\main.py", line 14, in
th = threading.Thread(target=send, kwargs=({'ip': conn}))
NameError: name 'conn' is not defined

How to fix this error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2022-03-21
@GroMan_L

1. At the moment the Thread constructor is called, the conn variable does not yet exist. You need to create a thread when it has already received a value.
2. Don't call the run() method. It will be called by itself, in a separate thread. To start this thread, you need to call start(). And keep in mind that send() works for you once, and stops.
I would suggest getting some practice with threading, for starters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question