The code below is a simple chat client. I start a local tcp server with netcat -l 8000 then connect with it by the running the script below. Depending on whether i start t1 or t2 first. I can either read from the server or not. I also notice, with the print statement, that i seem to be getting empty message on reading from terminal using both sys.readline and input functions.
I have also tried with threads instead of processes and the result is the same.
Edit: based on the response given by @paulsm4 i used ncat instead of netcat for as my server. this resulted in something crazier happening. Instead of netcat/nc if I use ncat -k -l -m 100 8000 and replace Process with Thread. The code works as it should. But when I use Process the code breaks down.
import sys
import socket
from multiprocessing import Process
from time import sleep
def connect(host, port):
s = socket.socket()
s.connect((host, port))
return s
def send_message(host, port):
s = connect(host, port)
while True:
sleep(1)
message = None
try:
message = input('> ')
except EOFError:
print("try failed")
pass
print('message is ', message)
if message:
val = s.send(message.encode('utf8'))
print('message sent')
def receive(host, port):
s = connect(host, port)
while True:
sleep(1)
message = s.recv(1024).decode('utf8')
print('\n', message)
def main(host, port):
t1 = Process(target=send_message, args=(host, port))
t2 = Process(target=receive, args=(host, port))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == '__main__':
host, port = sys.argv[1], int(sys.argv[2])
main(host, port)