2017-10-10 38 views
-2

我很有趣的客戶端發送消息到Python服務器。收到[錯誤數據] ..在Python中的Soket編程

客戶端:client.send( 「1」) 服務器端:

d=clientsocket.recv(1024) 
if (d=="1"): 
    print(" Correct value") 

它不會打印正確的值。我知道recv的錯誤,因爲我不知道它是如何工作的。任何人都可以請幫我解決這個問題。

+0

什麼樣的價值有* d *後來呢? – guidot

+0

具有諷刺意義的是,當我打印d時,屏幕上的值爲1.實際上我很困惑>>>> – Hayder

+0

最有可能的是,客戶端和服務器有不同的表示數字的想法。 Unicode,UTF8,ASCII ......請注意,在Python 2.x中,默認是擴展ASCII,而在3.x中是unicode。還有填充不可打印的零字節...... – guidot

回答

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() 
+0

謝謝。但是,我已經嘗試過您的建議,結果仍然是一樣的。它不會打印「正確的值」。 – Hayder

+0

它應該工作。你可能有其他問題。只需打印'd'的值並檢查。 –

+0

@Hayder,我在這裏添加一個服務器和客戶端程序,它按照您的期望運行。希望這會有所幫助。如果您需要任何幫助,請告訴我。 –

相關問題