Any help on how I can get this to take more than one client, and why not now? Thanks!
Also, is there something I am doing wrong with this code? I did mostly Python 2 tutorials because I can't find them for Python 3.4
Here is my 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 + "\n") f.close() def Main(): host = str(socket.gethostbyname(socket.gethostname())) port = 5000 print(host + ":" + str(port) + "\n") 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)) Thread(target=clientHandler(c)).start() s.close() if __name__ == "__main__": Main()
And here is my client code:
import socket def Main(): print("Send 'q' to exit\n") 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()
source share