How to create Server Using Socket and press Enter to shutdown the server python socket?
The following program will help to understand the concept of Python Socket and Create a simple server using Socket.
Required Libraries/Modules :
Socket: A network socket is a two way communication structure that enables the two way communication.
time
threading
keyboard
/*;==========================================
; Title: create Server Using Socket and press Enter to shutdown the server python socket? (Threading, Socket, Time, Keyboard, Server).
; Author: codenaive Santosh Kumar
; Date: 18 Dec 2021
; Programming Language: Python
;==========================================*/
from socket import *
from time import ctime
import threading
import keyboard
Table of Contents
Define Variables
HOST = "localhost"
PORT = 10040
ADDRESS= (HOST,PORT)
server= socket(AF_INET,SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)
Define Function that shutdown the sever as
def shutdown_server():
server.close()
Define Server and Client connection which start the communication between two end points
def server_client_connection():
while True:
try:
print("watting for connection...")
(client,address) = server.accept()
print("... connected from : ",address)
client.send(bytes(ctime()+"\n Have a nice day !",encoding="ascii"))
client.close();
except:
server.close()
print("Server Shutdown...");
break
Close the connection on keyboard enter button pressed
def close_the_connection():
while True:
if keyboard.is_pressed('q'):
t3=threading.Thread(target=shutdown_server()).start();
break;
Creating threads and start the server
try:
t1=threading.Thread(target= server_client_connection).start()
t2=threading.Thread(target= close_the_connection).start()
except:
print("Error: unable to start thread")
Output
Socket Server Side
watting for connection...
... connected from : ('127.0.0.1', 56346)
watting for connection...
Client using Telnet
C:\codenaive>telnet localhost 10080
Mon Jan 18 01:55:01 2021
Have a nice day !
Connection to host lost.
Leave a Reply