forked from sharunrajeev/YourFirstContribution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatClient.py
53 lines (44 loc) · 1.03 KB
/
chatClient.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
import socket, select, string, sys
#Helper function (formatting)
def display() :
you="You: "
sys.stdout.write(you)
sys.stdout.flush()
def main():
# Provide the Host IP address
host = "192.168.10.127"
port = 5678
# Asks for a new username
name=input("\nCREATING NEW ID:\nEnter Username: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connecting host
try:
s.connect((host, port))
except :
print("Can't connect to the server")
sys.exit()
# if connected
s.send(name.encode("utf-8"))
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('DISCONNECTED!')
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()