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.