-
Notifications
You must be signed in to change notification settings - Fork 2
/
Chat_V1.0.py
102 lines (89 loc) · 3 KB
/
Chat_V1.0.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
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
94
95
96
97
98
99
100
101
102
import socket
import sys
import threading
import subprocess
import struct
import pickle
#test branch
class Chat:
def __init__(self):
self.__pseudo = input("enter username: \n")
self.__port = None
self.__ip = None
self._lsUser = {}
self._handlers = {
'/exit': self._exit,
'/quit': self._quit,
'/join': self._join,
'/send': self._send,
'/address': self._client,
'/user': self._user,
'/server': self._server,
}
def run(self):
self.__address = None
self.__running = True
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 self._handlers:
try:
self._handlers[command]() if param == '' else self._handlers[command](param)
except:
print("Erreur lors de l'exécution de la commande.")
else:
print('Command inconnue:', command)
def _chat(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 _exit(self):
self._send("disconnect")
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
def _client(self):
print(self.__address)
def _user(self):
self.__user = subprocess.Popen(["whoami"], stdout=subprocess.PIPE)
print(self.__user.communicate()[0].decode().rstrip())
if __name__ == '__main__':
if len(sys.argv) == 3:
Chat().run()
else:
Chat().run()