So…sup?
anomit | June 5, 2008After relaxing for 5 days and staying away from the internet as much as possible, I’m back to some serious work.
Wrote a client and server process in python where the client sends inorder arithmetic expressions(not parenthesized, as of yet) and the server evaluates them and returns the result to the client. Pretty lame but I think it was good for an hour’s effort
. And Harsh, if you are thinking it is a threaded server, sorry its not
Coming to the other thing I’m working on, it is simulation of a network model with SSFNet and I won’t lie, at the moment I am not able make any head or tail of how to proceed with the work.
If you don’t wanna take the trouble of downloading the files and just want to check the code, read on:
*****SERVER*******
#!/usr/bin/env python
import socket
#dictionary that maintains the priority values
oper={'/':4,'*':3,'+':2,'-':1,'#':0}
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 8881))
sock.listen(5)
# the operator and operand stacks
opndstck=[]
operstck=['#']
def evaluate(s):
global operstck,opndstck
for i in range(len(s)):
ch=s[i]
if ch.isdigit(): opndstck.append(ch)
else:
"""If incoming element is a digit, put it on operand stack
else if priority of incoming operand is greater than or same as
operand stacktop, put it in the stack else pop required elements,
perform operation and continue"""
if oper[ch]>=oper[operstck[len(operstck)-1]]: operstck.append(ch)
else:
popAndEval(operstck,opndstck)
operstck.append(ch)
#to evaluate the residue operands
if len(opndstck)>1:
while True:
if len(opndstck)==1: break
popAndEval(operstck,opndstck)
return opndstck.pop()
def calc(oper1,ch,oper2):
if ch=='+': return oper1+oper2
elif ch=='-': return oper1-oper2
elif ch=='*': return oper1*oper2
elif ch=='/': return float(oper1)/float(oper2)
def popAndEval(opst,opnst):
opnd2=int(opnst.pop())
opnd1=int(opnst.pop())
opr=opst.pop()
res=calc(opnd1,opr,opnd2)
opnst.append(res)
try:
while True:
newSocket, address = sock.accept( )
while True:
recvd=newSocket.recv(8192)
if not recvd: break
#print recvd
result=evaluate(recvd)
newSocket.sendall(str(result))
newSocket.close()
finally:
sock.close()
*******CLIENT*********
import socket ,sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8881))
try:
while True:
print 'Enter:'
data=sys.stdin.readlines()
for each in data:
line=each.rstrip().splitlines()
sock.sendall(line[0])
response = sock.recv(8192)
print "Received:", response
finally:
sock.close()






