Skip to main content
gamedev.net
🔒 Locked

Handling a client in python

Started by nto 3 replies 1k views
Original Post
nto
nto
Hey everybody! I'm writing a network client for a simple tank game in python. At the moment I'm using a nonblocking socket and checking for input in the following way:

def run(self):
	self.running = 1
	
	while self.running:
		#make sure we're not using all cpu on just checking for input
		pygame.time.delay(50)
	
		#if there's no data to be read, it'll throw an exception with error code 11, it just means there's no data
		#currently to be read
		
		#with self.lock:
		try:
			result = self.sock.recv(1024)
			if result == '':
				print "Server quit."
			else:
				self.buf.append(result)
			
		except socket.error, (errno, s):
			if errno == 11:
				print "checked."
			else:
				self.running = 0
		except socket.herror, (h_errno, s):
			print h_errno, s
		except socket.gaierror, (errno, s):
			print errno, s
		except socket.timeout, s:
			print s
		except:
			print "Unknown error: ", sys.exc_info()[0]
			self.running = 0

I know this is absolutely horrible at the moment. I was thinking of maybe using select() instead on the client socket to see if it's ready for read and write. I don't know if this is smart to be doing on a client, since anything I've ever read always used it for a server that had to handle multiple clients. The point of making my client nonblocking is that I can send information at once when pressing a button. If I was using a blocking client, it'd block everytime I tried receiving from the server. My current approach is heavy on the CPU, so I'd really appreciate suggestions on how to improve it :-) Thanks in advance, nto.
nto
nto
Thanks a lot for the response, I was not sure if using select() on a client was frowned upon, but it seems it's not so I'll definitely be using it :-)
Antheus
Antheus
Twisted

Not only does it handle the networking, it also takes care of all the safety and scalability issues (such as this: "#make sure we're not using all cpu on just checking for input" - which is just bad).
nto
nto
Hey Antheus - thanks for your input, again again :)

I will definitely look into Twisted in my next project, but since I'm in the early stages of learning python I'd like for this very small project to be coded using normal unix sockets :-)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.