-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
67 lines (51 loc) · 1.79 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
#bin/python
#client
import sys
import socket
import select
import signal
def sigint_handler(signum, frame):
print '\n user interrupt ! shutting down'
print "[info] shutting down Chat server \n\n"
sys.exit()
signal.signal(signal.SIGINT, sigint_handler)
def chat_client():
if(len(sys.argv) < 4) :
print 'Usage : python client.py hostname port Name'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
uname=sys.argv[3]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Sorry , Unable to connect Check Ip or Port'
sys.exit()
print 'Connected to Chat server . You can start sending messages'
sys.stdout.write('[Me :] '); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])
for sock in ready_to_read:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()
else :
# user entered a message
msg = sys.stdin.readline()
msg = '['+ uname + ':]' +msg
s.send(msg)
sys.stdout.write('[Me] '); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())