Home > front end >  TypeError: a bytes-like object is required, not 'str' in my server
TypeError: a bytes-like object is required, not 'str' in my server

Time:04-10

When I create a server and a clint, I cannot send commands to them this code server to connect clint

:-

import socket

s = socket.socket()
h="192.168.1.2"
p=665
s.bind((h, p))
print ("YOUR SESSION HAS BEEN CREATED IN PORT : ", p)
s.listen(1)
v, addr = s.accept()
print("SUCCESS CONECTION ...", addr)
mssge = input ("==> ")
while mssge != 'e':
    v.send(mssge)
    data = v.recv(1024)
    print (data)
    mssge = input ("==> ")
s.close()

and i go to deffrant terminal and rin clint code and this code clint :-

import subprocess
import socket

s= socket.socket()
h="192.168.1.2"
p=665
s.connect((h, p))
while True:
        data=s.recv(1024)
        if not data:
                break

        co = subprocess.Popen(data, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        ct = co.stdout.read()   co.stderr.read()
        cf = str(ct)
        s.send(cf)
s.close()

after connect when i right any commend I have a problem and this error :-

YOUR SESSION HAS BEEN CREATED IN PORT :  665
SUCCESS CONECTION ... ('192.168.1.2', 49508)
==> ls
Traceback (most recent call last):
  File "/root/i.py", line 13, in <module>
    v.send(mssge)
TypeError: a bytes-like object is required, not 'str' 

please some help

CodePudding user response:

Socket Programming always transfers data in bytes(set of eight 0s and 1s) When you send, the data you send must be of bytes format.

arr = bytes(mssg, 'utf-8')

or

arr = bytes(mssg, 'ascii')

can convert your message to bytes, then send this.

On receiving end, Convert these bytes back to str object with

mssg = recieved.decode("utf-8")

CodePudding user response:

umm actually, v.send() requires a bytes-like object, not str, so that input()’s value is a str so that it cannot be. and you can also use this :

v.send(b”msg” b” “ * (128 - len(b”msg”)))

so that if multi-messages can be received because all message len are 64 letters

for receive : v.recv(64)

that’s my answer :D

CodePudding user response:

You must declare your IP address as a byte-string, not a str. This is done by adding a b before the string :

s = socket.socket()
h = b"192.168.1.2"
p = 665
s.connect((h, p))

You can also use the str.encode() method :

s = socket.socket()
h = "192.168.1.2"
p = 665
s.connect((str.encode(h), p))
  • Related