0

I was trying to make a simple chat application using the socket module in Python. In my client.py file I created two functions, one for writing and one for receiving messages from the server. As it must be run simultaneously, I used the threading module. But it's not working and I don't have a clue why. Here's my code:

import socket
import threading

SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
HEADER = 1024
FORMAT = "utf-8"
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((SERVER, PORT))

def write():
    while True:
        message = input()
        socket.send(message.encode(FORMAT))
threading.Thread(write())
def receive():
    while True:
        try:
            msg = socket.recv(HEADER).decode(FORMAT)
            print(msg)
        except:
            print('You have been disconnected!')
            socket.close()
            break
         
write_thread = threading.Thread(target=write())
recv_thread = threading.Thread(target=receive())
recv_thread.start()
write_thread.start()
  • 1
    What is your problem? Does it have an error, or wrong output? What should the code do? – Leo Mar 12 '22 at 11:15

1 Answers1

0

Things to fix in the future:

  1. (Line 4): I think what you want to do is SERVER = "localhost"
  2. (Line 15): This is unused

Error:

write_thread = threading.Thread(target=write())
recv_thread = threading.Thread(target=receive())

Should be(else you call the functions instead of giving them as a parameter):

write_thread = threading.Thread(target=write)
recv_thread = threading.Thread(target=receive)
Xyndra
  • 110
  • 1
  • 11