Below is the Python code for a simple game i had to create now i am having difficulty seperating the code to play the game over a client and server using sockets. any help would be appreciated
import random
rannum = random.randrange(0,10,1)
print rannum
counter = 0
a=0
while(a==0):
guess = int(raw_input("What is your guess?: "))
counter = counter + 1
diff = abs(guess - rannum)
if(diff >5):
print "Way Off!"
elif(diff >2):
print "Close!"
elif (diff>1):
print "Closer!"
elif(diff >0):
print "Even Closer!"
elif (diff==0):
print "Correct"
name = str(raw_input("What is your name?: "))
print name + " Your score is: "
print counter
f = open('high_scores.txt', 'a')
score = str(counter)
f.write(name + " " + score + "\n")
f.close()
break
The client interface in your code is just the
raw_inputfunction andprintstatements. Effectively, all you need to do is turn those intorecvandsendcalls on a socket, and you’ve got a server. Or, more simply, wrap the socket inmakefileand just write and read lines:You can test this without even writing a client, just using
nc localhost 12345. (If you’re on Windows, you don’t havencbuilt-in; google “netcat Windows” and get yourself a copy.) Then just look at the docs forsocket.connectand you should be able to write the client side.Now, you may want to reorganize your interface a bit. Maybe the client should provide the prompts and format the results (so, e.g., you can have separate English and Spanish clients with the same server—or, even better, a nice GUI client). To do that, you need to design some kind of protocol for the client and server to use for communication. (In fact, even the trivial example above has an implicit protocol: every prompt, response, etc. is separated by newlines. I “cheated” by using
makefileandreadlineto handle that automatically. But figuring out how to separate messages—newlines, length-prefixing, etc.—is just the first step.)You also may want to consider whether you really want to design a “raw” protocol that sits on top of TCP, or use something that takes care of the low-level stuff for you (a web service, JSON-RPC over sockets, etc.) so you only need to write the application-specific stuff yourself.
Finally, this is a very, very bad server. It only accepts one client, and it does everything synchronously, so if the client screws up the server can’t recover. A real server needs what’s called a “reactor” or a “proactor” (you can built your own with
select.select, or useasyncoreor something third-party liketwisted), or needs to spawn a new thread or process for eachaccept.