Search code examples
pythonsocketspython-3.xtcpnetwork-programming

TypeError: a bytes-like object is required, not 'str'


I am trying to make a client-server model, being new to python network programming I am stuck on an error which states the following:-

tcpCliSoc.send('[%s] %s' % (bytes(ctime(), 'utf_8'), data)) TypeError: a bytes-like object is required, not 'str'

Here is the Server and client implementation

TCP server implementation

from socket import *  
from time import ctime

HOST = ''  
PORT = 21572  
ADDR = (HOST, PORT)  
BUFFSIZE = 1024  

tcpSerSoc = socket(AF_INET, SOCK_STREAM)

tcpSerSoc.bind(ADDR)
tcpSerSoc.listen(5)

while True:  
    print("waiting for connection......")  
    tcpCliSoc, addr = tcpSerSoc.accept()  
    print("connected from", addr)  

    while True:  
        data = tcpCliSoc.recv(BUFFSIZE)
        if not data:
            break
        tcpCliSoc.send('[%s] %s' % (bytes(ctime(), 'utf_8'), data))
    tcpCliSoc.close()
tcpSerSoc.close()

TCP client implementation

from socket import *

__author__ = 'Lamer'

HOST = 'localhost'
PORT = 21572
ADDR = (HOST, PORT)
BUFFSIZE = 1024

tcpCliSoc = socket(AF_INET, SOCK_STREAM)
tcpCliSoc.connect(ADDR)

while True:
    data = input('>')
    if not data:
        break
    tcpCliSoc.send(data.encode())
    data = tcpCliSoc.recv(BUFFSIZE)
    if not data:
        break
    print(data.decode(encoding='utf-8'))

tcpCliSoc.close()

Solution

  • The string interpolation is creating a string, not a bytes object:

    >>> '%s foo' % b'bar'
    "b'bar' foo"
    

    (Notice that the result is of type str -- And it has a 'b' and some quotes inserted in it that you probably don't want).

    You probably want to interpolate bytes with bytes:

    >>> b'%s foo' % b'bar'
    b'bar foo'
    

    Or, in your code:

    tcpCliSoc.send(b'[%s] %s' % (bytes(ctime(), 'utf_8'), data))