-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
executable file
·61 lines (52 loc) · 1.91 KB
/
client.py
File metadata and controls
executable file
·61 lines (52 loc) · 1.91 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
#!/usr/bin/env python
"""
An chat client that allows the user to send multiple lines to the server.
Entering '/quit' will disconnect the client.
"""
import select
import socket
import sys
class Client(object):
def __init__(self):
self.host = ''
self.port = 5000
self.size = 1024
self.server_socket = None
self.socket_connections = []
def connect_to_host(self):
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.connect((self.host, self.port))
print 'Connected to chat server. You can start sending messages.'
self.prompt()
except socket.error, (code, message):
print "There was an error connecting. Error code: {code} Message: {message}".format(code=code, message=message)
sys.exit(1)
def prompt(self):
sys.stdout.write('[Me]: ')
sys.stdout.flush()
def run(self):
self.connect_to_host()
self.socket_connections = [self.server_socket, sys.stdin]
running = True
while running:
read_sockets, write_sockets, error_sockets = select.select(self.socket_connections, [], [])
for s in read_sockets:
# handle incoming message from chat server
if s == self.server_socket:
data = s.recv(self.size)
if not data:
print '\rDisconnected from chat server.'
s.close()
sys.exit(1)
else:
sys.stdout.write(data)
self.prompt()
# send client messages to the chat server
else:
data = sys.stdin.readline()
self.server_socket.send(data)
self.prompt()
if __name__ == "__main__":
c = Client()
c.run()