简体   繁体   中英

Sending and Receiving information with Sockets in Python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM