Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active March 16, 2016 17:40
Show Gist options
  • Save dboyliao/d61aafb8d88875221b98 to your computer and use it in GitHub Desktop.
Save dboyliao/d61aafb8d88875221b98 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# A simple fibonacci number server using TCP/IP,
# which can handle multiple clients.
from __future__ import print_function
from socket import *
import argparse
import os, sys
cache = {0: 1, 1:1}
MAX_BYTES = 1024
MAX_NUM_CLIENTS = 10
def fibo(n):
if n in cache:
return cache[n]
else:
cache[n] = fibo(n-1) + fibo(n-2)
return cache[n]
def server(ip, port):
sock = socket(AF_INET, SOCK_STREAM)
sock.bind((ip, port))
print("Fibonacci Server version 1.0")
print("Listening at {}:{}".format(*sock.getsockname()))
greeting = "Welcome to fibonacci server using TCP/IP..."
sock.listen(MAX_NUM_CLIENTS)
clients = []
while True:
client, address = sock.accept()
# I need a fork here.....
newPID = os.fork()
if newPID == 0:
client.send(greeting)
while True:
print("child", os.getpid())
data = client.recv(20)
if data != "":
print("Client sending: {}".format(data))
try:
n = int(data)
except ValueError:
client.send("Invalid data...")
continue
result = fibo(n)
client.send(str(result))
else:
client.send("Closing connection....")
client.close()
sys.exit(0)
else:
clients.append(address)
print("Connected clients: {}".format(clients))
def client(ip, port):
sock = socket(AF_INET, SOCK_STREAM)
print("Connecting to {}:{}....".format(ip, port))
sock.connect((ip, port))
msg = sock.recv(1000)
print(msg)
while True:
n = raw_input("Enter an integer: ")
if n == "":
print("Closing socket....")
sock.close()
break
sock.send(n)
result = sock.recv(MAX_BYTES)
print("Recieving from server: {}".format(result))
if __name__ == "__main__":
choices = {"client": client, "server": server}
parser = argparse.ArgumentParser()
parser.add_argument("role", choices = choices)
parser.add_argument("-p", "--port", type = int, dest = "p")
args = parser.parse_args()
function = choices[args.role]
function("127.0.0.1", args.p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment