net_tcp_server.py

# =========================================================
# receive data
# From: pymotw.com/2/socket/tcp.html
# ---------------------------------------------------------
# Open firewall:
# sudo ufw allow 10000/tcp
# =========================================================

import socket as sk

# create a TCP/IP socket

sock = sk.socket(sk.AF_INET,sk.SOCK_STREAM)

# bind the socket to a server address and port

#addr = 'localhost'
#port = 10000
#saddress = (addr,port)

port = 10000

saddress = ('',port)          # accept any connection

print('connecting to {}'.format(saddress))  

sock.bind(saddress)

# listen for incomming connections

sock.listen(1)

while True:

    print('waiting for connection')

    conn,client = sock.accept()

    try:
        print('connection from {}'.format(client))

        while True:

            msg = conn.recv(16)

            print('msg len = {}'.format(len(msg)))

            print('msg = "{}"'.format(msg))

            print('msg from {}'.format(client))

            if not msg:
                break

    finally:         # no matter what, close the connection

        # close the connection

        print('closing socket')

        conn.close()