我很有趣的客户端发送消息到Python服务器。收到[错误数据] ..在Python中的Soket编程
客户端:client.send( “1”) 服务器端:
d=clientsocket.recv(1024)
if (d=="1"):
print(" Correct value")
它不会打印正确的值。我知道recv的错误,因为我不知道它是如何工作的。任何人都可以请帮我解决这个问题。
我很有趣的客户端发送消息到Python服务器。收到[错误数据] ..在Python中的Soket编程
客户端:client.send( “1”) 服务器端:
d=clientsocket.recv(1024)
if (d=="1"):
print(" Correct value")
它不会打印正确的值。我知道recv的错误,因为我不知道它是如何工作的。任何人都可以请帮我解决这个问题。
你只需要简单的修改才能正常工作吧: -
在客户端正确象下面这样: -
client.send("1".encode())
在服务器正确象下面这样: -
d=clientsocket.recv(1024).decode()
if (d=="1"):
print(" Correct value")
我创建一个适合你的客户端和服务器,它在Python 3.4中工作正常。请尝试和检查:
这是你的服务器
import socket
import sys
HOST = "localhost"
PORT = 8000
print("Creating socket...")
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Binding socket...")
try:
sc.bind((HOST, PORT))
except socket.error as err:
print("Error binding socket, {}, {}".format(err[0], err[1]))
print("bound Successful")
# Configure below how many client you want that server can listen to simultaneously
sc.listen(2)
print("Server is listening on {}:{}".format(HOST, PORT))
while True:
conn, addr = sc.accept()
print("Connection from: " + str(addr))
print("Receiving data from client\n")
data = conn.recv(1024).decode()
print("Client says :" + data)
if(data == "2"):
print(" Ooh you are killing me with value :" + data)
conn.sendall(str.encode("\n I am server and you killed me with :" + data))
break;
elif(data == "1"):
print(" Correct value :" + data)
conn.sendall(str.encode("\n I am server and you hit me with correct value:" + data))
else:
print(" You are sending a wrong value :" + data)
conn.sendall(str.encode("\n I am server and you hit me with wrong value :" + data))
sc.close()
,现在你的客户是在这里: -
import socket
import sys
HOST = "localhost"
PORT = 8000
print("creating socket")
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting to host")
try:
sc.connect((HOST, PORT))
except socket.error as err:
print("Error: could not connect to host, {}, {}".format(err[0], err[1]))
sys.exit()
print("Connection established to host")
message = "1" # Run client 3 times with value message = '1' and '5' and '2'
sc.send(message.encode())
data = sc.recv(1024).decode()
print("Server response is : " + data)
sc.close()
谢谢。但是,我已经尝试过您的建议,结果仍然是一样的。它不会打印“正确的值”。 – Hayder
它应该工作。你可能有其他问题。只需打印'd'的值并检查。 –
@Hayder,我在这里添加一个服务器和客户端程序,它按照您的期望运行。希望这会有所帮助。如果您需要任何帮助,请告诉我。 –
什么样的价值有* d *后来呢? – guidot
具有讽刺意义的是,当我打印d时,屏幕上的值为1.实际上我很困惑>>>> – Hayder
最有可能的是,客户端和服务器有不同的表示数字的想法。 Unicode,UTF8,ASCII ......请注意,在Python 2.x中,默认是扩展ASCII,而在3.x中是unicode。还有填充不可打印的零字节...... – guidot