import socket
import threading

HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
DISCONNECT_MESSAGE = "[DISCONNECT!]"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((SERVER,PORT))

fhand = open('try.dat','a')

def handle_client(conn, addr):
	print(f"[NEW CONNECTION] {addr} connected.")
	connected = True

	while connected:
		msg = conn.recv(1024).decode("utf-8")
		fhand.write(msg)
		if not msg:
			break
		if msg == DISCONNECT_MESSAGE:
			print("entered here:")
			connected = False

		
	fhand.close()
	print("Connection disconnected")		
	conn.close()


def start():
	server.listen()
	print(f"[LISTENING] Server is listening on {SERVER}")
	while True:
		conn, addr = server.accept()
		thread = threading.Thread(target = handle_client, args=(conn, addr))
		thread.start()
		print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")

print("[STARTING] server is starting...")
start()








