-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
93 lines (77 loc) · 1.94 KB
/
client.py
File metadata and controls
93 lines (77 loc) · 1.94 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
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
import socket
import sys
from chat_thread import ChatThread
class Client(object):
def __init__(self, host, port):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.connect((host, port))
except socket.error, error_msg:
print error_msg
print "Unable to connect."
sys.exit()
print "Connected."
def login(self):
"""Send the name and starts the message thread
This function sending an entered name and
receiving response from server.
If response is empty - there is some throuble on the server
and exiting from program
else - login
"""
nickname = raw_input("Enter your name: ")
self.socket.send(nickname)
self.nickname = self.socket.recv(1024)
if not self.nickname:
print "Server error."
self.close()
sys.exit()
print "Your name is: " + self.nickname
msg_thread = ChatThread(20, self.recv_other)
msg_thread.daemon = True
msg_thread.start()
def chat(self):
print "Welcome in the chat room!"
print "You can start typing a message."
while True:
msg = raw_input()
try:
self.socket.send(msg)
except socket.error:
print "Server is offline"
break
def recv_other(self, threadId):
"""Receive messages from other people
This function represents a new thread, which
receiving messages from other users and
printing them
If message from server is empty - server was
turned off
"""
while True:
msg = self.socket.recv(4096)
if not msg:
print "Server is offline now.",
print "Press enter to exit."
self.close()
sys.exit()
else:
print msg
def close(self):
"""Send signal to server and close socket
This function sending empty message, which means,
that user exiting from the program
"""
try:
self.socket.send("")
except:
pass
print "Disconecting..."
self.socket.close()
client = Client("localhost", 2713)
try:
client.login()
client.chat()
except KeyboardInterrupt:
client.close()
sys.exit()