Message transmission on TCP/IP server with ctrl+c int handling, Python3
<p>i'm just started to learn Python, and i can't implement a good solution.</p>

<p>I want to write a client/server which allows you to send messages (like: texted, entered, texted, entered) on server until you press Ctrl+C interruption, and this int should close the socket both on server and client. </p>

<p>My very basic and, i suppose, very common client/server example on Python, but as you know - this pair is for single shot, and program is closing.</p>

<p>client.py</p>

<pre><code>import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFERSIZE = 1024

sock = socket.socket()
sock.connect((TCP_IP, TCP_PORT))

msg = input('Enter your text: ')
sock.send(msg.encode())
data = sock.recv(BUFFERSIZE).decode()
sock.close()

print('Recieved data: ',data)
</code></pre>

<p>server.py</p>

<pre><code>import socket
import sys

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024

sock = socket.socket()
sock.bind((TCP_IP, TCP_PORT))
sock.listen(1)

conn, addr = sock.accept()
print('Connection address:\nIP:',addr[0])
print('Port:',addr[1])
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    msg = data.decode()
    print('Recieved data: ', msg)
    conn.send(data)
conn.close()
</code></pre>

<p>Any suggestions?</p>

<p>Add a <code>try...finally</code> to the bottom part like so:</p>

<pre><code>try:
    while 1:
        data = conn.recv(BUFFER_SIZE)
        if not data: break
        msg = data.decode()
        print('Recieved data: ', msg)
        conn.send(data)
finally:
    conn.close()
</code></pre>

<p>Ctrl+C raises <code>KeyboardInterrupt</code> exception. When it does, the <code>finally</code> will be called, and safely close the socket.</p>

<p>The same can be done to the client in order to close it client-side:</p>

<pre><code>try:
    msg = input('Enter your text: ')
    sock.send(msg.encode())
    data = sock.recv(BUFFERSIZE).decode()
finally:
    sock.close()
</code></pre>

python sockets