0

I am currently creating a TCP socket server in python. The server is supposed to receive data in json form from a special connected client. The server is then supposed to distribute the data to all connected clients.

My problem is I am able to receive the data from the client and unpack it into the different json objects. But, whenever I try to distribute (send) the same json data to the rest of the clients it won't work. However if I send out dummy data, aka not the data received from the specific client, it all works like it is supposed to.

So the problem is that the receiving part and sending part of the server is not functioning together. I know this is possible, but it just won't work.

As mentioned, it works when I use dummy data to send to all clients. It leads me to think that it cannot send out the same data as it receives even though it is supposed to be able to.

Example of the problem:

def run(self):
  while conn:
    while True:
      try:
        # The receiving part
        data = conn.recv(2048)
        data = json.loads(data)
        x = data.get("X")
        z = data.get("X")


        # The sending part
        # It is to mention that I am looping through all clients,
        # so sending to all clients is not the problem.
        with client_list:
          for c in CLIENTS:
            message = json.dumps({"Title": "Coords", "X": x, "Z": z})
            conn.sendall(coords.encode())
      except Exception:
        pass

8
  • BTW have you tried not swallowing the exception? Maybe something interesting happening in your code that you are oblivious of. Commented Jun 17, 2019 at 18:20
  • Why are you using the same conn to both send and receive? Do you suppose to send data back to the original sender? This looks more like request-response that forwarding data "to the rest of the clients". Commented Jun 17, 2019 at 18:23
  • I get a JSONDecodeError: Expecting value: line 1 column 1 (Char 0) error if I do not swallow it. Even without the exception I am able to receive the data but I get the error Commented Jun 17, 2019 at 18:24
  • Before I send it back, I loop though all clients listed in a list. Commented Jun 17, 2019 at 18:25
  • python with client_list: for c in CLIENTS: coords = bla bla conn.sendall(coords.encode()) Is how I loop though all clients connected Commented Jun 17, 2019 at 18:26

1 Answer 1

1

I fixed it. When I looped though all the connected clients, I was still using conn to send. Had to use the c instead

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.