GroupChat Developments
12:05 PM
So, I was able to achieve a successful communication between two computers connected over the same wifi network using python sockets. One of the problems that I encountered was that it kept dropping some packets which I sent for reasons I don't know. Still, long way to go.. Here is the code..
from socket import *
import threading
import json
import sys
def keep_recieving(s):
while True:
m=s.recvfrom(54545)
incoming_json = json.loads(m[0])
print('\r')
if incoming_json['type'] == 'connect':
print(incoming_json['name'] + ' Joined')
elif incoming_json['type'] == 'message':
if name == incoming_json['from']:
#print('You: '+incoming_json['message'])
pass
else:
print(incoming_json['from'] + ": "+incoming_json['message'])
#print('You: ', end='')
def send_message(cs, name, words):
json_output = json.dumps({"type": "message", "from": name, "message": words})
cs.sendto(bytes(json_output, 'utf8'), ('255.255.255.255', 54545))
isServer = False
name = input('Enter your Name : ')
initialize = json.dumps({"type": "connect", "name": name})
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
cs.sendto(bytes(initialize, 'utf8'), ('255.255.255.255', 54545))
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('',54545))
thread = threading.Thread(target=keep_recieving, args=(s,))
thread.start()
print('Type exit to leave chat!')
words = input('You: ')
print('\n')
while words != 'exit':
send_thread = threading.Thread(target=send_message, args=(cs, name, words))
send_thread.start()
words = input('You: ')
print('\n')
12:47 PM
Today's coding session was much better. I tried creating a program using python Tkinter, that will display all the online users in a network.
First, I made a ping thread, which would ping the network broadcast address after every 500 milliseconds. This will ensure that all users get to know that the user is still online.Then I created a new_user list which another recieving thread would populate, if it got any new user, and which the draw function would pop the users from and update the GUI.
Also, if a user is inactive for 5 seconds, that is, the computer does not recieve any ping from that user in 5 seconds, then that user will be treated as disconnected, and the GUI will update.
Here is the code:
from socket import *
import time
from threading import *
import json
import tkinter as tk
new_users = []
def keep_recieving(s):
time.sleep(4)
#users.append('Heroshipma')
#print(users)
while True:
m=s.recvfrom(12345)
incoming_json = json.loads(m[0])
if incoming_json['type'] == 'connect' and incoming_json['name'] not in [user['name'] for user in users] and incoming_json['name'] not in [user['name'] for user in new_users]:
print(incoming_json['name'] + " Connected")
new_users.append({'name': incoming_json['name'], 'time': time.time()})
##----------Add users to new_user list if it is not currently added-------
elif incoming_json['type'] == 'connect':
for i in range(0, len(users)):
if users[i]['name'] == incoming_json['name']:
users[i]['time'] = time.time()
def ping_network(cs):
while True:
cs.sendto(bytes(initialize, 'utf8'), ('255.255.255.255', 12345))
time.sleep(0.5)
noLabel = None
def draw():
# if len(users) < 5:
# users.append('HIBAMBE')
# main_window.update()
for i in range(0, len(users)):
if time.time() - users[i]['time'] > 5:
print(users[i]['name'] + " Disconnected")
users.pop(i)
main_frame.winfo_children()[i].destroy()
while len(new_users) != 0:
new_user = new_users.pop()
user_btn = tk.Button(main_frame, text = new_user['name'], width=25)
user_btn.pack()
users.append(new_user)
main_window.after(500, draw)
name = input('Enter your Name : ')
#name = "Prakhar"
initialize = json.dumps({"type": "connect", "name": name})
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
ping_network_thread = Thread(target=ping_network, args=(cs,))
ping_network_thread.start()
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('',12345))
thread = Thread(target=keep_recieving, args=(s,))
thread.start()
users = []
main_window = tk.Tk()
main_frame = tk.Frame(main_window)
main_frame.pack()
main_window.title('Users online')
for user in users:
user_btn = tk.Button(main_frame, text = user, width=25)
user_btn.pack()
main_window.after(500, draw)
main_window.mainloop()
inp = input('Enter command')
print(inp)
Comments
Post a Comment