-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
49 lines (32 loc) · 1.56 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import socket
import threading
import datetime
def handle_client(client_soc, address):
print(f"Connection from {address} has been established!")
file=open('file.txt', 'w')
print('New file Created at: '+str(datetime.datetime.now()))
while True:
message = client_soc.recv(1024)
file.write('['+str(datetime.datetime.now())+']')
file.write(message.decode('utf-8'))
file.flush()
print('File Saved at: '+str(datetime.datetime.now()))
# print(message) #bytes to string message using utf-8
# file.close()
# print('File closed at: '+str(datetime.datetime.now()))
# if(message=='end\r'):
# print("System Message: closing connection with ", str(address))
# client_soc.close()
def main():
#define socket object
s = socket.socket()#socket.AF_INET, socket.SOCK_STREAM) # AF_INET---->IPV4, STREAM---->TCP
#now bind the socket object
s.bind(('192.168.137.1',8002)) #bind to a tuple, it has IP and a port number
s.listen(5) # it will have a queue of 5 if overloaded
while True:
clientSocket, address = s.accept() #Address is tuple of local host and clinet, this is also blocking so that reduandant threads arent made
#print(f"Connection from {address} has been established!")
#clientsocket.send(bytes("Welcome to the server!", "utf-8")) #send info to client socket
threading.Thread(target=handle_client, args=(clientSocket, address, )).start()
print('server is listening')
main()