-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
104 lines (100 loc) · 4.83 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import socket
import sys
import json
import select
class Client:
def __init__(self, hostname, port):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(2)
self.connect(socket)
self.name=None
def connect(self, socket):
try:
self.socket.connect((host, port))
print "\nSuccessfully connected to {0} on port {1}. ".format(host, port)
#self.socket.send("{command: 'groups'}") #get list of groups
except:
print 'Unable to connect to {0} on port {1}'.format(host,port)
sys.exit()
def handle_command(self,msg):
msg_info={"command":msg[0].lower()}
if msg[0].lower()=="h" or msg[0].lower()=="help":
print "Possible commands are: 'grouppost', 'groupjoin', 'groups', 'groupusers', 'groupleave', or 'groupmessage'."
return None
elif msg[0].lower()=="grouppost":
#get all info about message from user and add to array
msg_info['groupId']=raw_input("Enter index of group you want to send message to:") or "1"
msg_info['subject']=raw_input("Enter message subject: ") or "subject1"
msg_info['message']=raw_input("Enter message body: ") or "body1"
elif msg[0].lower()=="groupjoin":
#get a groupid if user didn't specify one as param of command, then add to msg_info
msg_info['groupId']=msg[1] if len(msg)>1 else (raw_input("Enter groupId: ") or "1")
elif msg[0].lower()=="groups":
#do nothing, just send message
pass
elif msg[0].lower()=="groupusers":
#get a groupid if user didn't specify one as param of command, then add to msg_info
msg_info['groupId']=msg[1] if len(msg)>1 else (raw_input("Enter groupId: ") or "1")
elif msg[0].lower()=="groupleave":
#get a groupid if user didn't specify one as param of command, then add to msg_info
msg_info['groupId']=msg[1] if len(msg)>1 else (raw_input("Enter groupId: ") or "1")
elif msg[0].lower()=="groupmessage":
#get a groupid and messageid if user didn't specify as param of command, then add to msg_info
msg_info['groupId']=msg[1] if len(msg)>1 else (raw_input("Enter groupId: ") or "1")
msg_info['messageId']=msg[1] if len(msg)>1 else (raw_input("Enter messageId: ") or "1")
else:
print "Invalid command entered!"
return None
#json encode and send the message to server
json_message=json.dumps(msg_info)
#print "sending message: "+json_message
self.socket.send(json_message+"\n")
return None
def start(self):
while True:
socket_list = [sys.stdin, self.socket]
ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])
for sock in ready_to_read:
if sock == self.socket: # Message from server
data = sock.recv(4096)
if not data : #if empty message, you're not connected
print '\nYou are disconnected.'
sys.exit()
else :
if is_json(data): #if message is json, parse and print appropriate parts
messages=json.loads(data)
for message in messages['messageContents']:
sys.stdout.write(message+"\n")
else: #otherwise just print the whole response
sys.stdout.write(data)
else : # User sending message to server
msg=sys.stdin.readline().split()
if len(msg)==0: #error if user doesn't input anything
print "Invalid command entered!"
else:
if self.name==None: #if no name set yet
self.name=msg[0]
#print "sending {0}".format(self.name)
self.socket.send(self.name+"\n")
else: #otherwise handle command
self.handle_command(msg)
def is_json(json_str):
"""
try to decode the string as if it were json. if an error is raised, it's not json.
"""
try:
json.loads(json_str)
except ValueError, e:
return False
return True
#program starts here
print "\nWelcome client, to this server thing!\n"
input_list=(raw_input("Enter command 'connect [hostname] [port]' to connect to a server: ") or 'connect localhost 9090').split()
if input_list[0].lower()!="connect" or len(input_list)!=3:
print "Error: Input should be 'connect [hostname] [port]'"
print "Exiting..."
sys.exit()
host = input_list[1]
port = int(input_list[2])
client = Client(host, port)
client.start()