Jhat

Playing around with python’s sockets, I created this shell-based chat. It works via LAN and lets you communicate through text messages.
Type ‘$help’ for a help menu.

Fred talking John talking Server


# Python 2.7.7 Code
# Jonathan Frech 21st of November, 2015
#         edited 22nd of November, 2015
#         edited 22nd of April   , 2016

# Jhat server
# Python 2.7.7 Code
# Jonathan Frech 21st of November, 2015
#         edited 22nd of November, 2015
#         edited 22nd of April   , 2016

# Jhat client

# import needed modules
import socket, threading, time, os

# get server name and port
print "***********************"
print " J h a t   S e r v e r "
print "***********************"
print

name = socket.gethostname()
port = None
while port == None:
		try:
				port = int( raw_input("Host server " + name + " on port ") )
		except:
				print "Port must be a number and not be used."

# start server
os.system("cls");os.system("clear")
print "***********************"
print " J h a t   S e r v e r "
print "***********************"
print
print "Server and port set."
print

SOCK = socket.socket()
SOCK.bind((name, port))
SOCK.listen(1)
SOCKETS = []

# broadcast message to all connected users
def broadcast(message, excluded = None):
	print message
	for s in SOCKETS:
		if s != excluded:
			s.send(message)

# listen for new sockets connecting to server
class LISTENFORSOCKETS(threading.Thread):
	# init
	def __init__(self):
		threading.Thread.__init__(self)
	
	# run function
	def run(self):
		while True:
			sock, addr = SOCK.accept()
			SOCKETTHREAD(sock).start()

# thread for individual users
class SOCKETTHREAD(threading.Thread):
	# init
	def __init__(self, _sock):
		self.sock = _sock
		SOCKETS.append(self.sock)
		threading.Thread.__init__(self)
	
	# run function
	def run(self):
		self.name = self.sock.recv(128)
		
		broadcast(self.name + " joined.", self.sock)
		while True:
			received = self.sock.recv(128)
			if received == "":
				# connection went down
				broadcast(self.name + " timed out.", self.sock)
				SOCKETS.remove(self.sock)
				return

			elif received == "quit":
				broadcast(self.name + " left.")
				SOCKETS.remove(self.sock)
				return
			else:
				broadcast("<" + self.name + "> " + received, self.sock)

# start listening
LISTENFORSOCKETS().start()
# import needed modules
import socket, time, threading, os

# establish a connection
def connect():
	print "***********************"
	print " J h a t   C l i e n t "
	print "***********************"
	print

	# get server name and port
	server = raw_input("Connect to server ")
	port = None
	while port == None:
		try:
			port = int( raw_input("Connect on port ") )
		except:
			print "Port must be a number."
	
	os.system("clear");os.system("cls")
	print "***********************"
	print " J h a t   C l i e n t "
	print "***********************"
	print
	print "Server and port set."
	print
	
	# get user 's name
	name = raw_input("Connect with name ")
	print
	
	# connect
	sock = socket.socket()
	print "Connecting to server..."
	while True:
		try:
			sock.connect((server, port))
			break
		except:
			print "Retrying connection to server..."
			time.sleep(1)

	print "Connection matched!"
	print

	# send name
	sock.send(name)
	
	# return socket
	return sock

# listen for server
class LISTENTHREAD(threading.Thread):
	# init
	def __init__(self, _sock):
		threading.Thread.__init__(self)
		self.sock = _sock
	
	# run function
	def run(self):
		while True:
			message = self.sock.recv(128)
			print message


# establish connection
SOCKET = connect()

# start listen thread
LISTEN = LISTENTHREAD(SOCKET)
LISTEN.daemon = True
LISTEN.start()

while True:
	inp = raw_input("")
	if inp == "":
		pass
	elif inp[0] == "$":
		if inp == "$quit":
			break
		elif inp in ["$help", "$?"]:
			print "Type to chat. '$quit' quits the shell, '$help' or '$?' opens this help text."
	else:
		SOCKET.send(inp)

print "\n"*10
os.system("clear");os.system("cls")
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s