Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Programming Hello I\'m trying to create server-client app where multiples

ID: 3913669 • Letter: P

Question

Python Programming

Hello I'm trying to create server-client app where multiples clients can collaborate painting when they join to a channel of their preference and also chat in between when they are colaborating: I have the code for an app I have created in the pass for booking flights which is a server and a client notice: I erased all of the methods I had used to create the app however I would like to know how can I structure the code in my server such that it takes the data from the painting app which I also have the code done in Tkinter but for a single user. I know I may have to use a timer fuction which would send the data back to the server and the server to the other clients are collaborating in the painting also probably a channel. Can someone give me a guide to what I need to do?  

#Server Code

import socket

import threading

import sys

import pickle

import json

class Server():

locked = False

def __init__(self, host="localhost", port=10000):

self.client = []

self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.sock.bind((str(host), int(port)))

self.sock.listen(10)

self.sock.setblocking(True) # Should be a blocking connection

self.prompt = 'Tool options:'

self.acceptCon()

# This function runs indefinitely

# It keeps on accepting & then initializing server code for connections

def take_input(self, client, prompt):

client.send(pickle.dumps(prompt))

client_response = '' # Initialize response variable

# Wait indefinitely until a response is seen using blocking connection

while client_response is None or len(client_response) == 0:

client_response = client.recv(1024)

# Parse the response

client_response = pickle.loads(client_response)

return client_response

def msg_to_all(self, msg, cliente):

for c in self.client:

try:

if c != cliente:

c.send(msg)

except:

self.client.remove(c)

def processCon(self, connection):

c = connection

response = self.take_input(

client=c,

prompt=self.prompt

)

print("Received ", response)

if response == 'draw':

self.sock.close()

sys.exit()

else:

pass

def acceptCon(self):

print("Connection has been established")

while True:

try:

conn, saddr = self.sock.accept()

conn.setblocking(True)

self.client.append(conn)

handler = threading.Thread(

target=self.processCon,

kwargs={"connection": conn}

)

handler.daemon = True

handler.start()

except:

pass

s = Server()

Client Code#

import socket

import threading

import sys

import pickle

class Client():

"""docstring for Cliente"""

def __init__(self, host="localhost", port=10000):

self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.sock.connect((str(host), int(port)))

msg_recv = threading.Thread(target=self.msg_recv)

msg_recv.daemon = True

msg_recv.start()

while True:

msg = input('-> ')

if msg != 'exit':

self.send_msg(msg)

else:

self.sock.close()

sys.exit()

def msg_recv(self):

while True:

try:

data = self.sock.recv(1024)

if data:

print(pickle.loads(data))

except:

pass

def send_msg(self, msg):

self.sock.send(pickle.dumps(msg))

c = Client()

Explanation / Answer

server code

import socket

import time

import os

from threading import Thread

folderPath = "Chat Logs"

filePath = folderPath + "/" + str(time.strftime("%H-%M-%S_%d-%m-%Y")) + ".txt"

def clientHandler(c):   

while True:

data = c.recv(1024)

if not data:

break

data = data.decode("UTF-8")

message = str(data[:data.index("§")])

nick = str(data[data.index("§")+1:])

print(nick + ": " + message)

saveChat(nick, message)

print(" Sending: " + data)

c.send(bytes(data, "UTF-8"))

c.close()

def saveChat(nick, message):

if not os.path.exists(folderPath):

os.makedirs(folderPath)

if not os.path.exists(filePath):

f = open(filePath, "a")

f.close()

f = open(filePath, "a")

f.write(nick + ": " + message + " ")

f.close()

def Main():

host = str(socket.gethostbyname(socket.gethostname()))

port = 5000

print(host + ":" + str(port) + " ")

Clients = int(input("Clients: "))

s = socket.socket()

s.bind((host, port))

s.listen(Clients)

for i in range(Clients):

c, addr = s.accept()

print("Connection from: " + str(addr))

Client code

import socket

def Main():

print("Send 'q' to exit ")

address = str(input("ip:port -> "))

nick = input("nick: ")

try:

if address.index(":") != 0:

host = address[:address.index(":")]

port = int(address[address.index(":")+1:])

except ValueError:

host = address

port = 5000

s = socket.socket()

s.connect((host, port))

message = input("-> ")

while message != "q":

s.send(bytes(message + "??" + nick, "UTF-8"))

data = s.recv(1024)

data = data.decode("UTF-8")

data2 = data

messageServer = str(data[:data.index("??")])

nickServer = str(data[data.index("??")+1:])

if not data == data2:

print(nickServer + ": " + messageServer)

message = input("-> ")

s.close()

if __name__ == "__main__":

Main()