1
+ import socket
2
+ import threading
3
+
4
+ format = 'utf-8'
5
+ header = 64
6
+ connected_msg = 'DISCONNECTED'
7
+
8
+ PORT = 5050
9
+ SERVER = socket .gethostbyname (socket .gethostname ())
10
+
11
+ server = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
12
+
13
+ ADDR = (SERVER , PORT )
14
+ server .bind (ADDR ) # The particular socket that we have just created is now bind with the declared port
15
+ # All the different connections are going to hit that particular socket at the time
16
+ # of connection
17
+
18
+ def start ():
19
+ server .listen ()
20
+ print (f"[SERVER-CHECK :: ] The server is running " )
21
+ print (f"[SERVER-IP-INFO :: ] { SERVER } " )
22
+ print ("Enter 'q' to stop this process " )
23
+ while True :
24
+ conn , addr = server .accept ()
25
+ thread = threading .Thread (target = handle_client , args = (conn , addr ))
26
+ thread .start ()
27
+ print (f"[ACTIVE CONNECTION :: ] { threading .activeCount () - 1 } " )
28
+ handle_client (conn , addr )
29
+ if (input () == 'q' ):
30
+ break
31
+ print ("The server is stopped !! watch you again" )
32
+
33
+
34
+
35
+ ## handling multiple clients together at the same time using threading
36
+ ## Each client will use a thread on server so no one will going to wait for any one
37
+
38
+ def handle_client (conn , addr ):
39
+ print (f"[New Connection :: ] { addr } is connected with this server " )
40
+ connected = True
41
+ while connected :
42
+ msg = conn .recv (1024 ).decode (format )
43
+ if msg :
44
+ if msg == connected_msg :
45
+ print (f"{ addr } is disconnected from the chat group " )
46
+ connected = False
47
+ conn .close ()
48
+
49
+ print (f"{ addr } => { msg } " )
50
+
51
+
52
+ print ("The server is going to start!! wait " )
53
+ start ()
0 commit comments