0

I have created two scripts which establish a client socket and server socket in localhost.

Server socket

import socket
from time import ctime

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

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

while True:
    print('waiting for connection .... ')
    print(ADDR)
    tcpClisoc,addr = tcpsersoc.accept()
    print('......connected from', addr)

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

    tcpClisoc.close()

tcpsersoc.close()

Client socket

from socket import *

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

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

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

tcpCliSock.close()

I'm still getting the below error despite converting the data into a bytes object. I'm using python 3.x

this is the error raised by the server socket

waiting for connection .... 
('', 21567)
......connected from ('127.0.0.1', 52859)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    import exampletcpserver
  File "C:/Python34\exampletcpserver.py", line 23, in <module>
    tcpClisoc.send('[%s]%s'%(bytes(ctime(),'UTF-8'),data))
TypeError: 'str' does not support the buffer interface

Please let me know where i'm going wrong.

1 Answer 1

1

You are trying to send a string, but sockets require you to send bytes. Use

tcpClisoc.send(('[%s]%s' % (ctime(), data.decode("UTF-8"))).encode("UTF-8"))

Python 3.5 will support the alternative

tcpClisoc.send(b'[%s]%s' % (bytes(ctime(), 'UTF-8'), data))
4
  • isnt that exactly what bytes(ctime(),'utf-8') does?
    – Jayaram
    Commented May 27, 2015 at 19:14
  • 1
    No. bytes(ctime(), 'utf-8') encodes this to bytes. By embedding this into a formatting operation on a string ("%s" % (..)), you again make a string out of it.
    – Phillip
    Commented May 27, 2015 at 19:17
  • ahhh :) thank you. it seems to be working now. I seem to be getting a response from the server. this is the below output when i type in 'hi' **[b' Thu May 28 00:50:54 2015'] b'hi' ** am i using decode wrong as well?
    – Jayaram
    Commented May 27, 2015 at 19:20
  • No, but you don't understand when to expect bytes and when to expect str yet. Do not worry, this bothers others (and me) as well. If you run into more problems like these, consider using Python 2 while experimenting. I'll update the answer such that you get what you expect..
    – Phillip
    Commented May 27, 2015 at 19:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.