The Server Thread

You may be wondering ... what happens after Abhi's memes are put in the "to deliver" bin?

Fear not! That will all be explained in this section.

The Code

def serverThread(clientele, serverChannel):
  while True:
    msg = serverChannel.get(True, None)
    print("msg recv: ", msg)
    msgList = msg.split(" ")
    senderID = msgList[0]
    instruction = msgList[1]
    details = " ".join(msgList[2:])
    if (details != ""):
      for cID in clientele:
        if cID != senderID:
          sendMsg = instruction + " " + senderID + " " + details + "\n"
          clientele[cID].send(sendMsg.encode())
          print("> sent to %s:" % cID, sendMsg[:-1])
    print()
    serverChannel.task_done()

On a high level, this takes the message from the bin, extracts important information (who sent it, instructions, details), and sends the message to all the clients. In the context of our example, the server thread is the mail truck. It takes Abhi's memes from the "to deliver" bin, assembles the package, and sends it to all Abhi's relatives.

Getting and Interpreting the Message

msg = serverChannel.get(True, None)
msgList = msg.split(" ")
senderID = msgList[0]
instruction = msgList[1]
details = " ".join(msgList[2:])

Pretty straightforward here. We take the message from the serverChannel (the "to deliver" bin), find out who sent it, the instruction that the clients will do, and the details (important data that guides the instruction). So to move Abhi right 5 pixels, senderID might be "Abhi", instruction might be "move", and details might be "+5 0" for +5 in the x direction and 0 in the y direction.

Most of this is just string formatting, so you can format the message however you'd like. This is just how we did it.

Sending the Message

for cID in clientele:
      if cID != senderID:
          sendMsg = instruction + " " + senderID + " " + details + "\n"
          clientele[cID].send(sendMsg.encode())

Nice and easy here too. We just format the message (you could change this if you want, just make sure be consistent with handleClient and your client-side implementation) and send an encoded message to all the clients. Why is it encoded? Well, sending Abhi's meme on an 8 x 11 is a no-no, so we have to format it by folding it up into an envelope first.

results matching ""

    No results matching ""