Python 套接字字符串 returns 发送后不同

Python socket string returns different after sended

我正在尝试使用此代码通过套接字传递字符串

p="YES"

s.send(p.encode())
---------------------
x = s.recv(10240).decode()

if x=="YES":
     print("YES")

您发送消息有误。 当您发送消息时,您的消息应以字节为单位发送

例如: s.send(bytes("Hello!", "utf-8))

这里,utf-8是编码。

所以在你的情况下,代码应该如下!


#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")

如果这不起作用或者您有进一步的疑问,请询问!