Skip to content

Instantly share code, notes, and snippets.

@Sahas-Ananth
Created March 27, 2021 07:57
Show Gist options
  • Save Sahas-Ananth/8c91c8d47b5e8718e7b607ba58d58bf6 to your computer and use it in GitHub Desktop.
Save Sahas-Ananth/8c91c8d47b5e8718e7b607ba58d58bf6 to your computer and use it in GitHub Desktop.
This gist containts two files a server and a client. The server echos back what is sent by the client. This is done by using socket programming in python
#!/usr/bin/env python3
# Library needed for socket programming
import socket
# Defining the header size
HEADER = 64
# Defining a port for the client to connect to
PORT = 5050
# Format specification of the message
FORMAT = "utf-8"
# A string to disconnect from the server
DISCONNECT_MESSAGE = "DISCONNECTED"
# Getting th IP address of the system
SERVER = socket.gethostbyname(socket.gethostname())
# Attaching the port and IP address together like 192.168.15.5 and 5050
ADDR = (SERVER, PORT)
# Creating a socket object with IPV4 protocol (AF_INET) and tcp agent (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connecting client to server
client.connect(ADDR)
def send_msg(msg):
# Encoding the message in specified format
message = msg.encode(FORMAT)
msg_length = len(message)
# Converting length of message to correct format
send_length = str(msg_length).encode(FORMAT)
# Attaching length of message to the header (the space betweeen the quotes is must)
send_length += b" " * (HEADER - len(send_length))
# Sending legth of message
client.send(send_length)
# Sending message
client.send(message)
# Printing if the message was recieved/ack
print(client.recv(2048).decode(FORMAT))
def main():
while True:
msgs = input("Enter a message to be sent to the server: ")
send_msg(msgs)
choice = input("Do you want to continue [y/n]: ")
if choice.lower() == "n":
break
send_msg(DISCONNECT_MESSAGE)
client.close()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nClosing Client\n")
#!/usr/bin/env python3
# Library needed for socket programming
import socket
# Library needed for multiple messages at the same time so multiple clients can use the same server
import threading
# Defining the header size
HEADER = 64
# Defining a port for the client to connect to
PORT = 5050
# Format specification of the message
FORMAT = "utf-8"
# A string to disconnect from the server
DISCONNECT_MESSAGE = "DISCONNECTED"
# Getting th IP address of the system
SERVER = socket.gethostbyname(socket.gethostname())
# Attaching the port and IP address together like 192.168.15.5 and 5050
ADDR = (SERVER, PORT)
# Creating a socket object with IPV4 protocol (AF_INET) and tcp agent (SOCK_STREAM)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connecting server to the port and locking it.
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected")
connected = True
while connected:
# Get message length
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
# Get message
msg = conn.recv(msg_length).decode(FORMAT)
# If message is equal to disconnect message break
if msg == DISCONNECT_MESSAGE:
connected = False
# Print message
print(f"[{addr}] {msg}")
# Send ack
conn.send("MESSAGE RECEIVED".encode(FORMAT))
# Close connection with client
conn.close()
def start():
print(f"[LISTENING] Server is active on {SERVER}")
# Listening on the port and ip
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
# Starting a new thread for a new client
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
if __name__ == "__main__":
try:
print("[STARTING] server is starting")
start()
except KeyboardInterrupt:
print("\n\nClosing server\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment