2

I'm using python 3.3.this is Server.py.Everything is fine both server and client are able to connect something might be wrong in here 'tcpcli.send('[%s]%s'%(bytes(ctime(),'utf-8'),data))'.help me out

from socket import *
from time import ctime

HOST=''
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

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

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

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

This is CLient.py

    from socket import *


HOST='127.0.0.1'
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

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


while True:
    data=input('>')
    if not data:
        break
    tcpcli.send(data)
    data=tcpcli.recv(BUFSIZ)
    if not data:
        break
    print (data.decode('utf-8'))

tcpcli.close()                 

When i'm running both they are working fine except I'm unable to send any data from client. I'm getting this error message.

tcpcli.send(data)
TypeError: 'str' does not support the buffer interface

2 Answers 2

2

You are using Python3. This means that, when using the CLI, input() will return a str object (equivalent to python2 unicode). It contains an internal representation of the unicode codepoints of the characters you entered. To send the data over a byte stream interface (such as pipes, sockets, …), you have to convert it to a bytes object. This is easily done by picking an encoding, such as UTF-8, and doing something like this:

data_raw = data.encode("utf-8")
tcpcli.send(data_raw)

You will have to adapt your servers code similarily, by first decoding the data you received from the client and reencoding it after you did string operations on it:

        data_decoded = data.decode("utf-8")
        reply = '[%s]%s' % (ctime(), data_decoded)
        tcpcli.send(reply.encode("utf-8"))
Sign up to request clarification or add additional context in comments.

1 Comment

tcpcli.send(bytes('[%s]%s' % (ctime(),data), 'utf-8')) is working great but i'm getting a 'b' extra in every output?ny idea
1

You are building unicode strings, not byte strings, and the socket interface doesn't support unicode strings. You'll need to encode the result of the string interpolation:

    tcpcli.send(bytes('[%s]%s' % (ctime(),data), 'utf-8'))

1 Comment

@Martin hey thanks...it worked i'm getting an extra b in output along with timestamp..ny help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.