[ Part 1 (Overview)Part 2Part 3Part 4Part 5Part 6 – Part 7 ]

Welcome to my blog’s first tutorial series!

Check out the video for details on the code!

What’s going on guys? Are ready to keep on coding?

In this part we won’t write too much code, mostly we’re going to focus on the building blocks to setup our server thread in the future.

This includes setting up a few variables, some new functions and some overall analysis into how the server thread is going to work.

I already explained in the overview how the program is going to operate in regards to handling clients but now we’re actually going under the hood.

Without further ado, let’s code!

Dive Into The Code

On the server script, we’re going to add two new functions:

  • CheckAddr(port, verbose)
  • AllocAddress()

The purpose of these functions will become clear later on, but for the time being we are going to use them to check if the IP address we chose as a host is available; while the second function will work to find an available port for the client to connect back to us (in the client thread, which will be developed later on).

Now let’s take a look at the actual code:

# Check if host and address is in use
def CheckAddr(port, verbose):
	sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	result = False
	try:
		sc.bind((HOST, port))
		result = True
		if verbose: print "\n[" + GetTime() + "] Host: " + str(HOST) + " and Port: " + str(port) + " is avaible..."
	except:
		if verbose: print "\n[" + GetTime() + "] Host: " + str(HOST) + " and Port: " + str(port) + " is currently in use."
	sc.close()
	time.sleep(interval)
	return result

# Function to allocate a port
def AllocAddress():
	global PTAV
	# Let's determine an available port for the new client
	while True:
		PTAV += 1
		if CheckAddr(PTAV, False): break
		# Limit port to 200
		if (PTAV-PORT) > 200: break

The CheckAddr(port, verbose) function simply tries to bind to the host we defined on part 2 and the port that we pass as an argument. If we successfully bind to it, then we know that address is available. As far as I know, this is one of the easiest ways to do this in Python.

The AllocAddress() function on the other hand will work to determine an available port. We simply add one to the PORT variable we set earlier and invoke the CheckAddr(port, verbose) function on that specific address.

Now basically what we want to do is, when our client connects to the server we’re going to wait for the second message, set up a new socket and connect back to the client. Which leads us to this part of the code:

s,a = c.accept()
if (s):
	print "\n[" + GetTime() + "] Connection from " + str(a)

	while True:
		msg = Receive(s)
		if len(str(msg)): print "\n[" + GetTime() + "] " + msg
		if msg == "Time for message number two! Ayyy ;)":
			print "\n[" + GetTime() + "] Negotiating private connection."

			time.sleep(interval)

			ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
			print "\n[" + GetTime() + "] Connecting back to client: " + str(a) + " (" + str(PORT) + ")"
			ns.connect((a[0], PORT))

			time.sleep(interval)

			Send(ns, "Can you receive a message tho?")

			# Ok, let's figure out a port for the client to connect to
			AllocAddress()

			time.sleep(interval)

			Send(ns, "Server is ready for client on port: " + str(PTAV))

			time.sleep(interval)

			break

Then we’ll send a test message to the client and once we confirm he can communicate with us, we allocate a new port and let the client know this is the port they should connect back for a private conversation.

So this is the port we will listen on our server thread once we fire it up.

Now let’s take a look at the client script:

s,a = c.accept()
if (s):
	print "\n[" + GetTime() + "] Connection from " + str(a)

	try:
		while True:
			msg = Receive(s)
			if len(str(msg)): print "\n[" + GetTime() + "] " + msg
	except KeyboardInterrupt:
		print ">>> Finished."

This is the only code being added to the client script for now.

After sending the two messages from the previous part, we’ll simply listen for a connection (remember we already had a socket set up for the main server?) and go ahead and print any messages we receive.

Download Code

Click here or above if you’d like to download the code.

That’s gonna be it for this part, check out the video for more analysis and feel free to leave any questions or comments down below.

Share: