Search code examples
pythonsocketsserver-sidepython-server-pages

How to stop my python server from shutting down after the first connection?


I started writing python servers this week, and I wrote just the simplest server I could make for an example. the server and client use sockets, the server listens to a socket, then sends back to the client what it got after saying "I got: ". I run both of those with CMD, and every time I connect to the server I need to turn it on again. I tried removing the sockets closing commands without success and many other methods with the same result, so if anyone has any idea how I can fix it I will be very grateful.

EDIT: the server's code: http://pastebin.com/X4sEwLPf the client's code: http://pastebin.com/uyDiUM4E


Solution

  • In the Server you are only accepting once a connection form a client. You have to put a loop arround the server code.

    import socket
    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0',8820))
    server_socket.listen(10)
    while True:
        (client_socket,client_adress) = server_socket.accept()
        client_input = client_socket.recv(1024)
        client_socket.send("I got : " + client_input)
        client_socket.close()
    server_socket.close()