import socket, time
#host = socket.gethostbyname(socket.gethostname())
host = '0.0.0.0'
port = 9873
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
quit = False
print('[ Server Started ]')
while not quit:
try:
data, addr = s.recvfrom(1024)
if addr not in clients:
clients.append(addr)
itsatime = time.strftime('%Y-%m-%d-%H.%M.%S', time.localtime())
print('[%s]=[%s]=[%s]/' % (addr[0], str(addr[1]), itsatime), end='')
print(data.decode('utf-8'))
for client in clients:
if addr != client:
s.sendto(data,client)
except:
print('\n[ Server Stopped ]')
quit = True
s.close()
import socket, threading, time
shutdown = False
join = False
def receving (name, sock):
while not shutdown:
try:
while True:
data, addr = sock.recvfrom(1024)
print(data.decode('utf-8'))
time.sleep(0.2)
except:
pass
host = socket.gethostbyname(socket.gethostname())
port = 0
#server = ('192.168.0.101', 9873)
server = ('127.0.0.1', 9873)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
alias = input('Name: ')
rT = threading.Thread(target = receving, args = ('RecvThread', s))
rT.start()
while shutdown == False:
if join == False:
s.sendto(('[%s] => join chat ' % alias).encode('utf-8'),server)
join = True
else:
try:
message = input()
if message != '':
s.sendto(('[%s] :: %s' % (alias, message)).encode('utf-8'), server)
time.sleep(0.2)
except:
s.sendto(('[%s] <= left chat ' % alias).encode('utf-8'), server)
shutdown = True
rT.join()
s.close()
$ python3 s.py
[ Server Started ]
[10.50.0.150]=[57276]=[2019-02-05-17.10.30]/[Den4ik] => join chat
[10.50.0.150]=[57276]=[2019-02-05-17.10.35]/[Den4ik] :: Hello
[10.50.0.150]=[57276]=[2019-02-05-17.10.39]/[Den4ik] <= left chat
^C
[ Server Stopped ]
$ python3 c.py
Name: Den4ik
Hello