'why server shut down?

So I created a server but when I run it, it keeps shutting down. why it happens?

import socket

my_server = socket.socket()
my_server.bind(("0.0.0.0", 8820))
my_server.listen()

on the other hand, when I add accept() function it doesn't shut down, but keeps running. why can't it just be waiting for calls?



Solution 1:[1]

socket.listen() is non-blocking therefore the line although is executed, proceeds with the execution to the next line. There's nothing more to execute, so the program exits and shuts down the opened socket - the server dies.

You need to create a loop that will be blocking by expecting a data retrieval or any other blocking operation such as described in the example section:

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:                 # the loop
            data = conn.recv(1024)  # the retrieval
            if not data: break
            conn.sendall(data)

The listen() function is only configuration step for the socket because a socket can listen but also do other operations such as only sending, or whatever you make it do. See the client program from the example section having no accept() anywhere hence not awaiting any connections to itself, only connect()-ing to already existing socket somewhere else:

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as 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('Received', repr(data))

Maybe Client-server model from Wikipedia will help understanding the general concept and the two-faced (or more, configuration thing) behavior of a network socket.

Also, unless you need to use the low-level socket, move away from it because there are just too many things you need to think about for making it at least usable not even secure. Instead, take a look at:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1