-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchat.py
More file actions
84 lines (75 loc) · 2.57 KB
/
Copy pathchat.py
File metadata and controls
84 lines (75 loc) · 2.57 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
#!/usr/bin/env python3
# chat.py
# author: Sébastien Combéfis
# version: February 15, 2016
import socket
import sys
import threading
class Chat():
def __init__(self, host=socket.gethostname(), port=5000):
s = socket.socket(type=socket.SOCK_DGRAM)
s.settimeout(0.5)
s.bind((host, port))
self.__s = s
print('Écoute sur {}:{}'.format(host, port))
def run(self):
handlers = {
'/exit': self._exit,
'/quit': self._quit,
'/join': self._join,
'/send': self._send
}
self.__running = True
self.__address = None
threading.Thread(target=self._receive).start()
while self.__running:
line = sys.stdin.readline().rstrip() + ' '
# Extract the command and the param
command = line[:line.index(' ')]
param = line[line.index(' ')+1:].rstrip()
# Call the command handler
if command in handlers:
try:
handlers[command]() if param == '' else handlers[command](param)
except:
print("Erreur lors de l'exécution de la commande.")
else:
print('Command inconnue:', command)
def _exit(self):
self.__running = False
self.__address = None
self.__s.close()
def _quit(self):
self.__address = None
def _join(self, param):
tokens = param.split(' ')
if len(tokens) == 2:
try:
self.__address = (socket.gethostbyaddr(tokens[0])[0], int(tokens[1]))
print('Connecté à {}:{}'.format(*self.__address))
except OSError:
print("Erreur lors de l'envoi du message.")
def _send(self, param):
if self.__address is not None:
try:
message = param.encode()
totalsent = 0
while totalsent < len(message):
sent = self.__s.sendto(message[totalsent:], self.__address)
totalsent += sent
except OSError:
print('Erreur lors de la réception du message.')
def _receive(self):
while self.__running:
try:
data, address = self.__s.recvfrom(1024)
print(data.decode())
except socket.timeout:
pass
except OSError:
return
if __name__ == '__main__':
if len(sys.argv) == 3:
Chat(sys.argv[1], int(sys.argv[2])).run()
else:
Chat().run()