# Client/Server TCP Socket programming

**URL:** <https://discuss.python.org/t/client-server-tcp-socket-programming/21701>\
**Category:** Python Help\
**Created:** [December 6, 2022, 1:23am UTC](https://discuss.python.org/t/client-server-tcp-socket-programming/21701 "2022-12-06T01:23:46Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![dstromberg](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/dstromberg/32/9047_2.png) [@dstromberg](https://discuss.python.org/u/dstromberg)\
**Post date:** [December 6, 2022, 4:03am UTC](https://discuss.python.org/t/client-server-tcp-socket-programming/21701/3 "2022-12-06T04:03:35Z")

</div>

client.py:

```auto
#!/usr/bin/env python3

"""shell_client.py for python3. Read data from a socket and, read a command from stdin, and send the command over the socket."""

import socket
import time

import bufsock

# Give the server time to start up.
time.sleep(1)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# We use port 4444 so we don't need to be root to run this.
s.connect(("127.0.0.1", 4444))
bs = bufsock.bufsock(s)

while True:
    # Read the prompt and print it.
    data = bs.readto(b'\n')
    print(data)
    # Read a command from the user's terminal.
    cmd = input()
    # Send the command to the server, terminated with a newline.
    bs.send(cmd.encode('utf-8'))
    bs.send(b'\n')
    bs.flush()
    # Read the command's always-one-line response and print it.
    data = bs.readto(b'\n')
    print(data)

```

server.py:

```auto
#!/usr/bin/env python3

"""Shell_server.py for python3. Accept a connection, read commands, execute them and send data back over the socket."""

import socket
import time

import bufsock

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# We use port 4444 so we don't need to be root to run this.
s.bind(("0.0.0.0", 4444))
s.listen(1)

while True:
    connexion, client_address = s.accept()
    print("connexion from: " + str(client_address))
    bs = bufsock.bufsock(connexion)
    while True:
        bs.send(b"Entrer cmd:\n")
        bs.flush()
        cmd = bs.readto(b'\n').rstrip(b'\n')
        if cmd == b'TIME':
            result = time.ctime().encode('utf-8')
            bs.send(result)
        else:
            bs.send(b'Unrecognized command: %s' % (cmd, ))
        bs.send(b'\n')
        bs.flush()

```

bufsock.py:  
[https://stromberg.dnsalias.org/~strombrg/bufsock.html](https://stromberg.dnsalias.org/~strombrg/bufsock.html)

…and I’m realizing tonight, that I should put bufsock on pypi. 🙂

---

_[View the full topic](https://discuss.python.org/t/client-server-tcp-socket-programming/21701)._
