Socket Server - TCP

In [1]:
# Modified based on http://cpp.wesc.webfactional.com/cpp3ev2/book3v2/ch02/tsTserv3.py

from socket import *
from time import ctime

HOST = '0.0.0.0'
PORT = 3333
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print('waiting for connection...')
    tcpCliSock, addr = tcpSerSock.accept()
    print('...connected from:', addr)

    while True:
        data = tcpCliSock.recv(BUFSIZ)
        if not data:
            break
        #tcpCliSock.send('[%s] %s' % (bytes(ctime(), 'utf-8'), data))
        tcpCliSock.send(bytes('[%s] %s' % (ctime(), data.decode('utf-8')), 'utf-8'))

    tcpCliSock.close()
tcpSerSock.close()
waiting for connection...
...connected from: ('127.0.0.1', 46280)
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-1-e009027e7029> in <module>()
     17 
     18     while True:
---> 19         data = tcpCliSock.recv(BUFSIZ)
     20         if not data:
     21             break

KeyboardInterrupt: