Python localhost server/client network code to add/subtract/multiply/divide two numbers?
I've recently been reading "Foundations of Python Network Programming" as I am interested in computer networks and for practice made up some code based off of the first few sample programs I saw in the book.. in this case I "wrote" a TCP server that binds to the localhost and a random port and a client that connects to the localhost. The client gives the server a string consisting of 2 numbers and an operation separated by spaces (i.e. '5 x 4') and the server evaluates this and returns the appropriate value.. my code is as 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 a connection from', sockname
print sc.getsockname(), 'is now connected to', sc.getpeername()
message = sc.recv(1024)
print 'The client wants to perform the 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]开发者_Go百科), 3)
sc.sendall('The result is ' + str(result))
sc.close()
print 'Reply sent as ' + str(result) + '.'
print
elif len(sys.argv) == 5 and sys.argv[1] == 'client':
s.connect((HOST, PORT))
print 'You are now 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: is this the best way to do this or is there a better way?
Thanks!
Twisted is about the best network engine on offer anywhere. It will handle everything you want in a nice and friendly chunk of code which is both CPU and IO friendly to your machine. http://twistedmatrix.com/trac/
I've used this for a few little things: http://docs.python.org/library/asynchat.html
As the docs say, it's more appropriate for i/o bound servers than cpu bound servers.
Going forward it is going to be much easier to use some sort of network package instead of just relying on the python standard library. I think 0MQ would be a good place to start, it has easy to work with and learn python bindings, most of what you are learning already still applies, and it is fast and efficient.
On top of that it doesn't tie you to the python language for all parts of the application, and it doesn't care about the transport method, intraprocess, interprocess, tcp...
http://zeromq.github.com/pyzmq/
精彩评论