I am using a tutorial that requires some server side code, but they don't show how to permanently run it. is there any way to do this, maybe with a web server? Here is the code:
import socket, threading
host = '127.0.0.1'
port = 7976
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print("Connected with {}".format(str(address)))
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print("Nickname is {}".format(nickname))
broadcast("{} joined!".format(nickname).encode('ascii'))
client.send('Connected to server!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
Related
So can someone please tell me how to have an admin-client shutting down the Server (server.py) in a socket multiple clients architecture? I want admin-client to type "shutdown" in client side then server will be shutdown. and right after submit, the server will call a function that shows network load graph . a graph with the number of requests per time slot.
Server:
`
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
data = self.csocket.recv(2048)
msg = data.decode()
if msg=='bye':
break
print ("from client", msg)
self.csocket.send(bytes(msg,'UTF-8'))
print ("Client at ", clientAddress , " disconnected...")
LOCALHOST = "127.0.0.1"
PORT = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
Client:
import socket
SERVER = "127.0.0.1"
PORT = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
client.sendall(bytes("This is from Client",'UTF-8'))
while True:
in_data = client.recv(1024)
print("From Server :" ,in_data.decode())
out_data = input()
client.sendall(bytes(out_data,'UTF-8'))
if out_data=='bye':
break
client.close()
`
I have tried
if message == "shutdown":
close()
exit(0)
but dont know how to apply it
I wanted to create a server-client chatbox room in python, where multiple clients could send messages in the chat box.
This is the server code
import threading
import socket
#setting up the local host and the local port
host = '127.0.0.1'
port = 9879
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port)) #hosting the server to the host
server.listen() #server listen to incoming connection
#list for client and their nicknames
clients = []
nicknames = []
#broadcast method to send message to all the clients connected to the server
def broadcast(message):
for client in clients:
client.send(message)
def handle (client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except: #if the connection is lost, discard the client
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f'{nickname} already left the chat!'.encode('ascii'))
nicknames.remove(nickname)
break
#function to receive connection
def receive():
while True:
client, address = server.accept()
print(f"Conncected with {str(address)}")
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f'The nickname of the client is {nickname}')
broadcast(f'{nickname} joined the chat!'.encode('ascii'))
client.send('Connected to the server!'.encode('ascii'))
#making thread for every client
thread = threading.Thread(target = handle, args = (client,))
thread.start()
print("Server is waiting for client...")
and this is the client code
import socket
import threading
#nickname prompt
nickname = input("Input your nickname: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#binding the client to the port
client.connect(('127.0.0.1', 9879))
def receive():
while True:
try:
message = client.recv(1024).decode('ascii')
if message == 'NICKNAME':
client.send(nickname.encode('ascii'))
else:
print(message)
except:
print("An error occurred!")
client.close()
break
def write():
while True:
message = f'{nickname}: {input("")}'
client.send(message.encode('ascii'))
#making the thread
receive_thread = threading.Thread(target = receive)
receive_thread.start()
write_thread = threading.Thread(target = write)
write_thread.start()
However, whenever i inputted the nickname in the command prompt there was an error
Traceback (most recent call last):
File "C:\Users\march\Documents\Programming\Pyhton\client.py", line 8, in <module>
client.connect(('127.0.0.1', 9879))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
I wonder what's the problem because the port for both server and client are the same and the port is available.
On your server code you're missing a call to the receive function that runs the while loop and puts the server on accept for connections.
The code becomes
import threading
import socket
#setting up the local host and the local port
host = '127.0.0.1'
port = 9879
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port)) #hosting the server to the host
server.listen() #server listen to incoming connection
#list for client and their nicknames
clients = []
nicknames = []
#broadcast method to send message to all the clients connected to the server
def broadcast(message):
for client in clients:
client.send(message)
def handle (client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except: #if the connection is lost, discard the client
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f'{nickname} already left the chat!'.encode('ascii'))
nicknames.remove(nickname)
break
#function to receive connection
def receive():
while True:
client, address = server.accept()
print(f"Conncected with {str(address)}")
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f'The nickname of the client is {nickname}')
broadcast(f'{nickname} joined the chat!'.encode('ascii'))
client.send('Connected to the server!'.encode('ascii'))
#making thread for every client
thread = threading.Thread(target = handle, args = (client,))
thread.start()
print("Server is waiting for client...")
receive() # runs the function that accepts for incoming connections
The client code should run the write() function on the main thread and not on another one, because it requires input from the stdin. You can change your code as follows in order to run the receiving routine on another thread and your "writing" function on the main one.
import socket
import threading
#nickname prompt
nickname = input("Input your nickname: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#binding the client to the port
client.connect(('127.0.0.1', 9879))
def receive():
while True:
try:
message = client.recv(1024).decode('ascii')
if message == 'NICKNAME':
client.send(nickname.encode('ascii'))
else:
print(message)
except:
print("An error occurred!")
client.close()
break
def write():
while True:
message = f'{nickname}: {input("")}'
client.send(message.encode('ascii'))
#making the thread
receive_thread = threading.Thread(target = receive)
receive_thread.start()
# on the main thread
write()
The cause of the Connection refused error was due to the fact that the server code immediately exited since the receive function was never actually called.
i have this server code:
import socket
import threading
host = "host"
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_list = []
color_list = []
server.bind((host, port))
server.listen()
def broadcast(message):
for client in client_list:
client.send(message.encode("ascii"))
def accept_conn():
while True:
conn, addr = server.accept()
if conn not in client_list:
client_list.append(conn)
conn.send("color".encode("ascii"))
color = conn.recv(1024).decode("ascii")
color_list.append(color)
message = conn.recv(1024).decode("ascii")
color_1 = color_list[client_list.index(conn)]
broadcast("[SERVER]recieved")
print(f"SERVER {host} RUNNING")
thread = threading.Thread(target=accept_conn)
thread.start()
and this client code:
import socket
import threading
host = "host"
port = 55555
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
color = input("enter the color: ")
def write():
while True:
message = input("")
client.send(message.encode("ascii"))
def recieve():
check = 1
while True:
message = client.recv(1024).decode("ascii")
if message == "color" and check == 1:
client.send(color.encode("ascii"))
check = 0
else:
print(message)
thread = threading.Thread(target=write)
thread2 = threading.Thread(target=recieve)
thread.start()
thread2.start()
now what this is supposed to do is recieve messages from the client and in response send to all connected clients the message recieved from the client.
right now im checking if it sends it to all clients by sending "recieved" from the server the client after every time the server recieves a message from the client.
the output looks like this:
enter the color: red
hi
[SERVER]recieved
im
the problem with this is that when i write the first message the server responds with "recieved" but after that it dosent which seems to me like its only running once.
would like some help on this.
I'm currently working on a multithreaded web server in Python which should be capable of processing HTTP requests sent from a browser or any other client programs.
I have a client.py file and a server.py file. Right now, I can run both of them on separate terminals and send messages from the client to the server.
What I want to do is to host the server on a localhost and send HTML files from the client to the server, so that the HTML files can be displayed on the server - hence on the localhost site. The server and client codes are down below. Help would be highly appreciated.
Thanks in advance!
Server.py -
import socket
import threading
IP = socket.gethostbyname(socket.gethostname())
PORT = 5566
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
DISCONNECT_MSG = "!DISCONNECT"
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg = conn.recv(SIZE).decode(FORMAT)
if msg == DISCONNECT_MSG:
connected = False
print(f"[{addr}] {msg}")
msg = f"Msg received: {msg}"
conn.send(msg.encode(FORMAT))
conn.close()
print("Server is starting...")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen()
print(f"Server is listening on {IP}:{PORT}")
while True:
conn, addr = server.accept()
try:
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}")
except IOError:
conn.send('\nHTTP/1.1 404 Not Found\n\n'.encode())
conn.close()
Client.py -
import socket
IP = socket.gethostbyname(socket.gethostname())
PORT = 5566
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
DISCONNECT_MSG = "!DISCONNECT"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
print(f"[CONNECTED] Client connected to server at {IP}:{PORT}")
connected = True
while connected:
msg = input("> ")
client.send(msg.encode(FORMAT))
if msg == DISCONNECT_MSG:
connected = False
else:
msg = client.recv(SIZE).decode(FORMAT)
print(f"[SERVER] {msg}")
So this code broadcasts to all the clients connected to it (including itself) but rather I want to broadcast to a specific client. How do I do that?
import socket, threading #Libraries import
host = '127.0.0.1' #LocalHost
port = 7978 #Choosing unreserved port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket initialization
server.bind((host, port)) #binding host and port to socket
server.listen()
clients = []
nicknames = []
def broadcast(message): #broadcast function declaration
for client in clients:
print(client, type(client))
client.send(message)
def handle(client):
while True:
try: #recieving valid messages from client
message = client.recv(1024)
broadcast(message)
except: #removing clients
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break
def receive(): #accepting multiple clients
while True:
client, address = server.accept()
print("Connected with {}".format(str(address)))
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print("Nickname is {}".format(nickname))
broadcast("{} joined!".format(nickname).encode('ascii'))
client.send('Connected to server!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
If a client sends message the server will broadcast the message to all clients including the client that sent the message. Is there a way to fix this issue?
Change broadcast function to the following:
import socket, threading #Libraries import
host = '127.0.0.1' #LocalHost
port = 7978 #Choosing unreserved port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket initialization
server.bind((host, port)) #binding host and port to socket
server.listen()
clients = []
nicknames = []
def broadcast(message, clientt): #broadcast function declaration
for client in clients:
if client == clientt:
continue
else:
client.send(message)
# for client in clients:
# print(client, type(client))
# client.send(message)
def handle(client):
while True:
try: #recieving valid messages from client
message = client.recv(1024)
broadcast(message, client)
except: #removing clients
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('ascii'), client)
nicknames.remove(nickname)
break
def receive(): #accepting multiple clients
while True:
client, address = server.accept()
print("Connected with {}".format(str(address)))
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print("Nickname is {}".format(nickname))
broadcast("{} joined!".format(nickname).encode('ascii'), client)
client.send('Connected to server!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()