-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathclient.py
More file actions
57 lines (46 loc) · 1.42 KB
/
client.py
File metadata and controls
57 lines (46 loc) · 1.42 KB
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
import socket, select, string, sys
#Helper function (formatting)
def display() :
you="\33[33m\33[1m"+" You: "+"\33[0m"
sys.stdout.write(you)
sys.stdout.flush()
def main():
if len(sys.argv)<2:
host = raw_input("Enter host ip address: ")
else:
host = sys.argv[1]
port = 5001
#asks for user name
name=raw_input("\33[34m\33[1m CREATING NEW ID:\n Enter username: \33[0m")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connecting host
try :
s.connect((host, port))
except :
print "\33[31m\33[1m Can't connect to the server \33[0m"
sys.exit()
#if connected
s.send(name)
display()
while 1:
socket_list = [sys.stdin, s]
# Get the list of sockets which are readable
rList, wList, error_list = select.select(socket_list , [], [])
for sock in rList:
#incoming message from server
if sock == s:
data = sock.recv(4096)
if not data :
print '\33[31m\33[1m \rDISCONNECTED!!\n \33[0m'
sys.exit()
else :
sys.stdout.write(data)
display()
#user entered a message
else :
msg=sys.stdin.readline()
s.send(msg)
display()
if __name__ == "__main__":
main()