I'm writing a small Python code that communicates over a socket but I'm having trouble making it so that sending and receiving are absolutely independent actions, i.e. not having to wait for a response in order to be able to send another message. My current code is as follows:
#!/usr/bin/python3
import argparse
import json
import socket
import time
import readline
parser = argparse.ArgumentParser(description='Client')
parser.add_argument("address", metavar= "Address", type=str,nargs=1, help="Server IP")
parser.add_argument("port",metavar="Port", type=str, nargs=1, help="Port to use")
args = parser.parse_args()
addr = args.address[0]
port = int(args.port[0])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting to {0} on port {1}".format(addr, port))
try:
sock.connect((addr, port))
print("Successfully connected to {0}".format(addr))
except Exception as e:
raise(e)
sock.settimeout(60)
while True:
msg = input("{0} | Out: ".format(time.strftime("%H:%M:%S")))
words = msg.split(" ")
if(words[0] == "connmobi"):
words = "connect MOBIPIN-02000152 D4:F5:13:6B:77:A6".split(" ")
data = json.dumps({"command":words[0],"args": [word for word in words[1:]]})
sock.send("{0}\n".format(data).encode())
try:
data = sock.recv(1024).decode().strip('\n')
except socket.timeout:
continue
print("{0} | In: {1}".format(time.strftime("%H:%M:%S"), data))
if data == "bye":
sock.close()
print("Socket closed")
break
How can I 'separate' the actions of receiving and reading from the socket?