我很有兴趣客户端向python服务器发送消息。
客户端:client.send(“1”) 服务器端:
d=clientsocket.recv(1024)
if (d=="1"):
print(" Correct value")
它不会打印正确的值。我知道recv的错误,因为我不知道它是如何工作的。有谁可以帮我解决这个问题。
答案 0 :(得分:0)
您只需要进行简单修改即可正常使用: -
客户端中的如下所示: -
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()