0

I have a code with server that i created the server is "proxy", the server get data from the user then send the data to the server' get answer from server' then send the answer to the user. I need the server to stop when the user presses ctrl + break or when i close the program.

import socket
LISTEN_PORT = 9090
SERVER_IP = "54.71.128.194"
SERVER_PORT = 92

# Create a TCP/IP socket
listening_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Binding to local port 9090
server_address = ('127.0.0.1', LISTEN_PORT)
listening_sock.bind(server_address)

# Listen for incoming connections
listening_sock.listen(1)
while True:
    #Create a new conversation socket
    client_soc, client_address = listening_sock.accept()
    client_msg = client_soc.recv(1024)
    client_msg = client_msg.decode()
    print(client_msg)

    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connecting to remote computer 9090
    server_address = (SERVER_IP, SERVER_PORT)
    sock.connect(server_address)
    msg = client_msg
    sock.sendall(msg.encode())
    server_msg = sock.recv(1024)
    server_msg = server_msg.decode()
    print(server_msg)
    server_msg = server_msg[:16]+"proxy "+server_msg[15:]
    msg = server_msg
    client_soc.sendall(msg.encode())
    print(msg)

# Closing the conversation socket
client_soc.close()
 # Closing the listening socket
listening_sock.close()
Alex123
  • 5
  • 2
  • Does this answer your question? [How do I capture SIGINT in Python?](https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python) – Rodrigo Rodrigues Apr 08 '22 at 13:59
  • What platform(s) must this work on? Does it specifically have to be `ctrl+break`? If `ctrl+c` is acceptable, you can try adding this at the top of the script `import signal; signal.signal(signal.SIGINT, signal.SIG_DFL)`. – ekhumoro Apr 08 '22 at 14:19
  • its have to be ctrl+break – Alex123 Apr 08 '22 at 14:26
  • @Alex123 `Ctrl+Break` is Windows-specific. What platform are you on? Why can't you use a different key combination? – ekhumoro Apr 08 '22 at 16:58

1 Answers1

0

You can create a break statement inside the loop. For example
pip install keyboard

import keyboard

while True:
   if keyboard.is_pressed('pause'):
      break

or

import keyboard

while not keyboard.is_pressed('pause'):
   print("loop")

keyboard.is_pressed(key) returns True if the key (combination) is pressed.
Dont know if this is the correct key, but this is simple adjustable. Keystroke combinations are written with plus: keyboard.is_pressed('shift+alt+s')
Docs: https://github.com/boppreh/keyboard#api