0 Replies - 579 Views - Last Post: 19 April 2014 - 10:39 AM Rate Topic: -----

#1 mr.nobody   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-April 14

Chat Client/Server Issues

Posted 19 April 2014 - 10:39 AM

Hello,
I have a problem and I can't get my head around it. I am making a chat server in python.
The first thing I tried to do after the code was giving to me is to make a python dictionary and store the USERNAMES inside of it. The issue here is that when a client connects through TELNET instead of updating the same dictionary it creates a new one and I don't get why ? The other issue is that when I use the command MESSAGE and I type a paramater hello it sends is to itself and if there are other connections they don't receive them.

Can someone give me a guidance where to look what to follow so I can fixed them ?

server.py - the function I am talking about is def OnMesssage
#---- Import Section ----#
import sys
from ex3utils import Server

class MyServer(Server):

 def onstart(self):
   # Print that the server is running
   print 'MyServer is running'

   # Initialise variables
   self.noOfConnections = 0 
   self.message = ''

 def onConnect(self,socket):
   # Count clients connected to the server
   self.noOfConnections += 1
   print 'Number of Users Connected: ' + str(self.noOfConnections)
   # Initiliase screenName variable
   socket.screenName = {}

 def onMessage(self, socket, message):

   # Command | Paramater Technique
   (command,sep, parameter) = message.strip().partition(' ')

   if (command == 'USERNAME'):
     socket.screenName.update({parameter:parameter})

   if (command == 'MESSAGE'):
        message = parameter
        socket.send(message)

 
   print 'Command is', command
   print 'Paramater is', parameter
   print 'Output', socket.screenName

   return True

 def onDisconnect(self, socket):
   self.noOfConnections -= 1

   # Print message that someone disconnected
   print 'Disconnected ' + str(self.noOfConnections)

   # Print message how many clients are left on the server
   print 'Clients left: ' + str(self.noOfConnections)

 def onstop(self):
   # Print message
   print 'MyServer is NOT running anymore'


# Parse the IP address and port you wish to listen on.
ip = sys.argv[1]
port = int(sys.argv[2])

# Create an my server.
server = MyServer()

# Start server
server.start(ip, port)




here is the utilities script
import threading
import time
import socket as socketlib


class Socket():
	"""
	Mutable wrapper class for sockets.
	"""

	def __init__(self, socket):
		# Store internal socket pointer
		self._socket = socket
	
	def send(self, msg):
		# Ensure a single new-line after the message
		self._socket.send("%s\n" % msg.strip())
		
	def close(self):
		self._socket.close()
		

class Receiver():
	"""
	A class for receiving newline delimited text commands on a socket.
	"""

	def __init__(self):
		# Protect access
		self._lock = threading.RLock()
		self._running = True

	def __call__(self, socket):
		"""Called for a connection."""
		# Set timeout on socket operations
		socket.settimeout(1)

		# Wrap socket for events
		wrappedSocket = Socket(socket)
		
		# Store the unprocessed data
		stored = ''
		chunk = ''
		
		# On connect!
		self._lock.acquire()
		self.onConnect(wrappedSocket)
		self._lock.release()
		
		# Loop so long as the receiver is still running
		while self.isRunning():
		
			# Take everything up to the first newline of the stored data
			(message, sep, rest) = stored.partition('\n')
			if sep == '': # If no newline is found, store more data...
				while self.isRunning():
					try:
						chunk = ''
						chunk = socket.recv(1024)
						stored += chunk
						break
					except socketlib.timeout:
						pass
					except:
						print 'EXCEPTION'
				
				# Empty chunk means disconnect
				if chunk == '':
					break;

				continue
			else: # ...otherwise store the rest
				stored = rest			
				
			# Process the command
			self._lock.acquire()
			success = self.onMessage(wrappedSocket, message)
			self._lock.release()
			
			if not success:
				break;

		# On disconnect!
		self._lock.acquire()
		self.onDisconnect(wrappedSocket)		
		self._lock.release()
		socket.close()
		del socket
		
		# On join!
		self.onJoin()
			
	def stop(self):
		"""Stop this receiver."""
		self._lock.acquire()
		self._running = False
		self._lock.release()
		
	def isRunning(self):
		"""Is this receiver still running?"""
		self._lock.acquire()
		running = self._running
		self._lock.release()
		return running
		
	def onConnect(self, socket):
		pass

	def onMessage(self, socket, message):
		pass

	def onDisconnect(self, socket):
		pass

	def onJoin(self):
		pass

		
		
class Server(Receiver):

	def start(self, ip, port):
		# Set up server socket
		serversocket = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM)
		serversocket.setsockopt(socketlib.SOL_SOCKET, socketlib.SO_REUSEADDR, 1)
		serversocket.bind((ip, int(port)))
		serversocket.listen(10)
		serversocket.settimeout(1)
		
		# On start!
		self.onstart()

		# Main connection loop
		threads = []
		while self.isRunning():
			try:
				(socket, address) = serversocket.accept()
				thread = threading.Thread(target = self, args = (socket,))
				threads.append(thread)
				thread.start()
			except socketlib.timeout:
				pass
			except:
				self.stop()

		# Wait for all threads
		while len(threads):
			threads.pop().join()

		# On stop!				
		self.onstop()

		return serversocket

	def onstart(self):
		pass

	def onstop(self):
		pass



class Client(Receiver):
	
	def start(self, ip, port):
		# Set up server socket
		self._socket = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM)
		self._socket.settimeout(1)
		self._socket.connect((ip, int(port)))

		# On start!
		self.onstart()

		# Start listening for incoming messages
		self._thread = threading.Thread(target = self, args = (self._socket,))
		self._thread.start()
		
	def send(self, message):
		# Send message to server
		self._lock.acquire()
		self._socket.send("%s\n" % message.strip())
		self._lock.release()
		time.sleep(0.5)

	def stop(self):
		# Stop event loop
		Receiver.stop(self)
		
		# Join thread
		if self._thread != threading.currentThread():
			self._thread.join()
		
		# On stop!
		self.onstop()		

	def onstart(self):
		pass

	def onstop(self):
		pass
		
	def onJoin(self):
		self.stop()



Is This A Good Question/Topic? 0
  • +

Page 1 of 1