I want to create a Socket Client and want to receive the answer if a message is sent in one function but also want to listen to all incoming data all the time.
The problem is, if I do both, the code stops executing as recv() seems to be a blocking function.
This is a quick overview:
Server.py
import socket
HOST = "127.0.0.1"
PORT = 6543
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print("Connected by ", addr)
while True:
data = conn.recv(1024)
conn.sendall(data)
Client.py
import socket
import time
import multiprocessing
HOST = "127.0.0.1"
PORT = 6543
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def keepAlive():
while True:
s.send(b"Keep Alive to be handled in keepAlive")
print(s.recv(1024), "received from keepAlive")
time.sleep(1)
def send():
while True:
s.send(b"Random message to be handled in listen")
time.sleep(1)
def listen():
while True:
print(s.recv(1024), "received from listen")
if __name__ == "__main__":
keepAliveProc = multiprocessing.Process(target=keepAlive)
listenProc = multiprocessing.Process(target=listen)
sendProc = multiprocessing.Process(target=send)
keepAliveProc.start()
listenProc.start()
sendProc.start()
But this will block and the Code doesn't continue. Can anyone help with this?
2 Answers 2
I don't think you need a res = socket.recv(1024) in your server block. You are not expecting a response from the client (listen()) as the client is not sending anything.
1 Comment
I don't have experience in python programming, but i did develop socket communication in java recently. If recv blocks program, then it blocks until it received some data. I think you need to change from multiproccessing to threads since multiproccessing is CPU bound and your communication is network based.
Maybe this can help: Python socket recv in thread
5 Comments
keepAlive message so be received in the keepAlive function, right after it was sent, and everything else in the listen() function. It's sending the message once, receives it in the wrong function (listen()) and then stops.Explore related questions
See similar questions with these tags.
listenandkeepAliveto know which data to receive? As per your design, both would be waiting for data at the same time.keepAlivefaster and get the answer right after sending... How would you solve this in general? Something like send and wait for response?