I'm trying to pass a string via socket using this code
p="YES"
s.send(p.encode())
---------------------
x = s.recv(10240)
if x=="YES":
print("YES")
CodePudding user response:
You have made a mistake in sending the message. when you send a message your message should be sent in bytes
For example:
s.send(bytes("Hello!", "utf-8))
Here, utf-8
is the encoding.
so in your case, the code should be as follows!
#client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = "YOUR IP"
port = "YOUR PORT"
s.connect((ip,port))
p = "YES"
s.send(bytes(p, "utf-8"))
#server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = "0.0.0.0"#leave it as 0.0.0.0 as it will be read as localhost
port = "YOUR PORT"
s.bind((ip,port))
s.listen(10) #can accept upto 10 connections
while True:
sc, address = s.accept()
msg = sc.recv(1024)
msg = msg.decode("utf-8)#since it was sent in utf-8 encoding, it has to be decoded from utf-8 only.
print(msg)
#or
if msg == "YES":
print("YES")
If this does not work or you have further queries, please ask!
CodePudding user response:
As Jason here said .encode()
on a string is just another way to convert it to bytes.
here is another answer for you. you didnt receive it properly
you never decoded the message so try this instead,
x = s.recv(10240)
x = x.decode()
print(x)