1

I'm playing with sockets in python, and I can't find a way to close my "server" connection in the command line. ctrl+c, ctrl+z do not work.

my server.py file:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1235))
s.listen(5)

while True:
  clientsocket, address = s.accept()
  print(f"connection from {address} has been established!")
  clientsocket.send(bytes("Welcome to the server!", "utf-8"))
  clientsocket.close()

if I make updates to this file I have to close the terminal and rerun the script. I have to change the port number because the original port stays occupied. The guy in the tutorial has to do the same thing, but I can't imagine that this is the best way to do things. Is there a command that will close the connection, clear the ports, etc., allowing me to restart the script?

  • I'm on Windows 10
  • SO_REUSEADDR does allow me to restart the script on the same port, however I am still not able to stop the script. I still have to close the terminal to stop the script.
JSum
  • 557
  • 7
  • 19

3 Answers3

0

You can get all open listen ports with

netstat -tulpn | FINDSTR LISTEN | FINDSTR PORTNUMBER (maybe need a bit change - not sure about windows commands.)

then kill the process.

ali sarkhosh
  • 163
  • 1
  • 11
0

You may also try below and see if it works

For closing server , use shutdown before close :

def close():
    server.shutdown(socket.SHUT_RDWR)
    server.close()

For reuse of address , use below before binding the socket :

server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Kaa
  • 144
  • 6
0

Maybe try doing:

import sys

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

while True:
  try:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("Welcome to the server!", "utf-8"))
    clientsocket.close()
  except KeyboardInterrupt:
    print(f"closing connection to {address}.")
    clientsocket.shutdown(socket.SHUT_RDWR)
    clientsocket.close()
    sys.exit()

This should allow you to use Ctrl + C to close your program AND let you restart it without changing the address.

alekala
  • 30
  • 6