net_tcp_client.py

# =========================================================
# send data
# From: pymotw.com/2/socket/tcp.html
# =========================================================

import socket as sk

# create a TCP/IP socket

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

# connect to server address and port

addr = 'localhost'
port = 10000

saddress = (addr,port)

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

sock.connect(saddress)

# send data

i = 0

try:

    print('sending messages')

    while True:

        msg = 'my message #{}'.format(i)

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

        print('sending message "{}"'.format(msg))

        sock.sendall(msg)

        if i > 4:
            break

        i += 1

finally:                 # no matter what, close the socket

    # close the connection

    sock.close()