I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side?
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
Close active connections and exit. It can be done with:
server.close()
exit(0)
To shutdown you socket server manually by calling server.close(), you whole code should be:
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
# call server.close() to shut down your server.
Related
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}")
This code is for sending and receiving between my PC and AWS Instance
I want to know whether the transmitted data is considered secure? or do I need something else to ensure the security of the transmitted data?
If the data is not encrypted, what is the addition to the code to make it secure?
code's client
import socket
HOST = "public ip of server"
PORT = 4444 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
server's code
server code
import socket
HOST = "0.0.0.0"
PORT = 4444 #open this in your router
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
I've set up my server.py and client.py with the socket module, is there a way you can connect to the internet through the client? What i mean is, I want to have the server connect to the client through it's own internet, and then from there have the client use its internet to browse the web. But I have no idea how to do this.
So is there something I can leverage to achiece this?
Server:
import socket, threading
from time import sleep
PORT = 5430
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTIONS] {addr} connected')
while True:
conn.recv(6000)
conn.close()
def start():
server.listen()
print(f'[LISTENING] Server is listening on {SERVER}')
while True:
conn, addr = server.accept()
thread = threading.Thread(target = handle_client, args = (conn,addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
print('[STARTNG] Server is starting')
start()
Client:
from time import sleep
import socket
PORT = 5430
SERVER = socket.gethostbyname(socket.gethostname())
FORMAT = 'utf-8'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
while True:
client.send('hi').encode(FORMAT)
conn.close()
I try to print out this code and the command in Pycharm looks like as it was looping through the code and no result displayed, I said that because the terminal doesn't complete its task, and the dollar sign doesn't appear. I need to know if that code results in any output from it. this code is a copy of some tutorial hence it's not created by me.
import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (HOST, PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ADDR)
s.listen()
print('running')
conn, addr = s.accept()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDR)
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
Also, I need to know what is the relationships between (WSGI, ASGI) and their relations with the socket in python.
The code following conn, addr = s.accept() never runs because s.accept is blocking. Move the client socket's code to a separate file and run it seperately.
Server code:
import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (HOST, PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ADDR)
s.listen()
print('running')
conn, addr = s.accept()
data = conn.recv(1024)
conn.close()
s.close()
print('Received', repr(data))
Client code:
import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (HOST, PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDR)
s.sendall(b'Hello, world')
s.close()
Note : This problem has been completely solved, as was am running client.py before server.py
Just got started with socket programming, I have created the below code and expecting to print some byte message, but it isn't doing that.
I just want to make the message available for any person on any
machine. But it's refusing by the machine to do that.
Here is my code:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.bind((socket.gethostname(), port))
s.listen()
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.connect(('192.168.0.1', port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Some images to better explain my errors:
Any help would be appreciated!!!
It looks like in the server.py script you use s.bind((socket.gethostname(), port)) where socket.gethostname() is a hostname, but in the client.py script you use s.connect(('192.168.0.1', port)) where '192.168.0.1' is the hostname you are trying to connect.
I think there you have socket.gethostname() != '192.168.0.1' and that's the problem.
Also, you can bind to all available IP addresses on the host using this solution Python socket bind to any IP?
Let's use listen_ip = socket.gethostbyname(socket.gethostname()) for connection since socket.gethostname() may return hostname instead of IP and it will not be solved by python dns resolver in local network if it was local name, not DNS.
and use it later as s.bind((listen_ip, port)) and s.connect((listen_ip, port))
After some debugging I've got a working solution for you
There are the scripts required.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12_048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
# or we can set it using env variable named SERVER_IP
if 'SERVER_IP' in os.environ:
host = os.environ['SERVER_IP']
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
In a chat conversation we concluded that the hardcoded IP in the question is not the correct one. This solution does have the IP he needed but it will be different in each case. Remeber that server.py needs to be launched first, and when you see the printed Server listening # IP:12048, write that IP in client.py and launch it. Client does need to be launched after seeing that line even if you already know the IP, as the server needs some time to be ready and the client will crash if it tries to connect to the server while it is not ready.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))