TCP communication using Socket module-Python3

Please see with the previous article. Python3 socket module and socket communication flow A simple example of TCP communication using the python3 socket module

environment

Python: 3.6 Required modules: colorama

Execution result and source code

Server side (for two socket communications)

server_side_img.jpg

import socket
from colored_print import print_msg


SERVER_ADDRESS = ('192.168.1.200', 8000)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(SERVER_ADDRESS)

sock.listen(0)

for i in range(2):
    try:
        conn_sock, client_address = sock.accept()
        print_msg('ac', 'The connection accepted.')
        print_msg('i', '{}:{} --------> {}:{}'
                  .format(client_address[0], client_address[1],
                          SERVER_ADDRESS[0], SERVER_ADDRESS[1]))

        # Receiving process
        amount_received = 0
        MSGLEN = int(conn_sock.recv(4))
        print_msg('i', 'MSGLEN: {}'.format(MSGLEN))

        while amount_received < MSGLEN:
            data = conn_sock.recv(min(MSGLEN - amount_received, 32))
            print_msg('i', 'received: {}'.format(data))
            amount_received += len(data)
            if not data:
                raise RuntimeError('The connected socket broken.')

            # Sending process
            conn_sock.send(data)
            print_msg('i', 'send: {}'.format(data))
    finally:
        conn_sock.close()
        print_msg('cl', 'The connection closed.')

Client side

client_side_img.jpg

import socket
from colored_print import print_msg


SERVER_ADDRESS = ('192.168.1.200', 8000)
MSG = 'Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do.'
MSGLEN = len(MSG)

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

try:
    sock.connect(SERVER_ADDRESS)
    print_msg('cn', 'The connection accepted')

    print_msg('i', 'MSGLEN: {}'.format(MSGLEN))
    sock.send(bytes(str(MSGLEN), 'utf-8').zfill(4))

    # Sending process
    sock.send(bytes(MSG, 'utf-8'))

    # Receiving process
    chunks = []
    amount_received = 0
    while amount_received < MSGLEN:
        data = sock.recv(min(MSGLEN - amount_received, 32))
        print_msg('i', 'received: {}'.format(data))
        amount_received += len(data)
        if not data:
            raise RuntimeError('The connected socket broken.')
        chunks.append(data)
finally:
    sock.close()
    print_msg('cl', 'The connection closed.')

result = '''
Result: [
    MSGLEN: {},
    Send: {},
    Received: {}
]
'''.format(MSGLEN, MSG, chunks)

print_msg('i', result)

Commentary

The break of the recv loop is

  1. Break when b'' comes.
  2. If you know the length of the message, break when the length of the received message becomes equal to the length of the message.

There are different types, but the problem with 1. is that b'' is passed even when communication is broken during communication. So, this time, I made a rule that the first 4 bytes to be sent is the length of the message.

Server side

One socket communication from [ACCEPT] to [CLOSE].

Send back as soon as you receive a message from a client.

Client side

One socket communication from [CONNECT] to [CLOSE].

colored_print Place the code below in the same directory.

colored_print.py


from colorama import Fore, Style


def print_msg(header, msg):
    '''header are i that is INFO or e that is ERROR'''

    if header == 'i':
        print(Fore.GREEN + '[INFO]',
              Style.RESET_ALL + msg)
    elif header == 'e':
        print(Fore.RED + '[ERROR]',
              Style.RESET_ALL + msg)
    elif header == 'ac':
        print(Fore.BLUE + '[ACCEPT]',
              Style.RESET_ALL + msg)
    elif header == 'cn':
        print(Fore.BLUE + '[CONNECT]',
              Style.RESET_ALL + msg)
    elif header == 'cl':
        print(Fore.BLUE + '[CLOSE]',
              Style.RESET_ALL + msg)
    else:
        print(Fore.RED + 'ERROR: header is an invalid value.'
              + Style.RESET_ALL)

Recommended Posts

TCP communication using Socket module-Python3
Socket communication using socketserver with python now
Socket communication with Python
WiringPi-SPI communication using Python
(Beginner) SSL socket communication
Communication between uWSGI and Nginx using Unix Domain Socket
Asynchronous http communication using asyncio
Socket communication with Python LEGO Mindstorms
Python3 socket module and socket communication flow
I tried server-client communication using tmux