networking - Python localhost server/client network code to add/subtract/multiply/divide two numbers? -
i've been reading "foundations of python network programming" interested in computer networks , practice made code based off of first few sample programs saw in book.. in case "wrote" tcp server binds localhost , random port , client connects localhost. client gives server string consisting of 2 numbers , operation separated spaces (i.e. '5 x 4') , server evaluates , returns appropriate value.. code follows:
#!/usr/bin/env python import socket, sys s = socket.socket(socket.af_inet, socket.sock_stream) host = '127.0.0.1' port = 1060 if sys.argv[1] == 'server': s.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) s.bind((host, port)) s.listen(1) while true: print 'now listening at: ', s.getsockname() sc, sockname = s.accept() print 'we have accepted connection from', sockname print sc.getsockname(), 'is connected to', sc.getpeername() message = sc.recv(1024) print 'the client wants perform operation: ' + message message = message.split() if message[1] == '+': result = float(message[0]) + float(message[2]) elif message[1] == '-': result = float(message[0]) - float(message[2]) elif message[1] == '*': result = round(float(message[0]) * float(message[2]), 3) elif message [1] == '/': result = round(float(message[0]) / float(message[2]), 3) sc.sendall('the result ' + str(result)) sc.close() print 'reply sent ' + str(result) + '.' print elif len(sys.argv) == 5 , sys.argv[1] == 'client': s.connect((host, port)) print 'you connected to: ', s.getsockname() s.sendall(sys.argv[2] + ' ' + sys.argv[3] + ' ' + sys.argv[4]) reply = s.recv(1024) print 'the return value is', repr(reply) s.close() else: print >>sys.stderr, 'usage: addstream.py server or addstream.py client num1 +/-/*// num2'
my question is: best way or there better way?
thanks!
twisted best network engine on offer anywhere. handle want in nice , friendly chunk of code both cpu , io friendly machine. http://twistedmatrix.com/trac/
Comments
Post a Comment