Python Chat Server (4 of 7)
[ Part 1 (Overview) – Part 2 – Part 3 – Part 4 – Part 5 – Part 6 – Part 7 ]
Welcome to my blog’s first tutorial series!
Ayyyyoooo guys! What’s good?
Continuing from my last post, its time to implement the server thread.
A lot of pieces are already in place to handle the server threads, so we should be able to get it done without too much hassle.
There are some minor code changes in the server script which I will only be covering in the video above, so if you’re only following the blog make sure to download the code at the end of the post and compare the changes.
Let’s write some codes!
Server Handler Code
# Server handler # -------------------------------------------- # This function will listen for connections as daemons # and keep connected in background. def ServerHandler(serverIP, serverPort, clientIP): sh = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sh.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sh.bind((serverIP, serverPort)) sh.listen(1) # Listen for 1 client, each server = 1 client z,b = sh.accept() if (z): print "\n[" + GetTime() + "] Connection from " + str(b) while True: msg = Receive(z) if len(str(msg)): print "\n[" + GetTime() + "] " + msg
There isn’t much to the server handler. Basically we fire up a socket using the supplied arguments serverIP and serverPort – this port is the one supplied by the AllocAddress() function we created in the previous part (will basically add +1 to the same port of the main server).
After that we’ll listen for a connection from client and simply print all the messages we receive. It’s important to note that this server thread will run as a daemon – meaning it will always be in the background.
# Let's start a new server thread to listen for single connection shtname = 'ServerT' + str(PTAV) print "\n[" + GetTime() + "] Starting server thread " + shtname sht = threading.Thread(name=shtname, target=ServerHandler, args=(HOST, PTAV, a[0])) servers.append(sht) sht.setDaemon(True) sht.start() time.sleep(interval) Send(ns, 'port: ' + str(PTAV)) print "\n[" + GetTime() + "] Server thread " + shtname + " open."
Now onto this code, which runs inside our “server testing” block. We’ll simply give our thread a name containing the allocated port, then fire it up in the background. After that we’ll go ahead and communicate the port so the client can connect back to it.
# Stay alive while threads are running while True: for x in servers: if x.isAlive(): time.sleep(interval)
Finally we need some code to keep the server script running while all server threads are alive, so this while loop will take care of that.
Client Script Code
There isn’t much going on in the client script this time around:
if msg[:4] == 'port': print "\n[" + GetTime() + " Connecting to: " + str(a[0]) + " on " + msg ps = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ps.connect((str(a[0]), int(msg[-5:]))) time.sleep(interval) # Finally open the private chat communication while True: ms = raw_input("\n[" + GetTime() + "] Enter message: ") if ms == 'quit': break else: Send(ps, ms)
Inside our main loop in the “client testing” block, we’ll add a condition to check when we receive a message containing the keyword ‘port’.
Then we’ll go ahead and extract the port from that message.
Afterwords we’ll open a while loop to enter the private chat mode.
Download Code
As I mentioned in the beginning, we’re keeping each part with little chunks of code to try to pass along some of the concepts and development process.
I recommend downloading the code and studying individual parts that you might not understand or simply leave any questions below!
Hope y’all enjoyed this part and cya next time!
Leave a Comment