我正在嘗試學習Socket編碼,並且編寫了一小段Process-to-Process通信。 這是Servercode:調用.recv(1024)和.send()兩次,沒有任何事情發生(Python)
import socket
s = socket.socket()
host = socket.gethostname()
port = 17752
s.bind((host, port))
s.listen(5)
while True:
(client, address) = s.accept()
print(address, 'just connected!')
message = input("Would you like to close the connection? (y/n)")
if message == 'y':
message = "False"
client.send(message.encode(encoding="utf_8"))
client.close()
break
elif message == 'n':
print("sending message...")
testing = "Do you want to close the connection?"
client.send(testing.encode(encoding='utf_8'))
print("sent!")
而且Clientcode:
import socket
client = socket.socket()
host = socket.gethostname()
port = 17752
client.connect((host, port))
while True:
print("awaiting closing message...")
closing = client.recv(1024)
closing = closing.decode(encoding='utf_8')
print("Closing message recieved and decoded")
if closing == 'False':
print("message is false, breaking loop")
break
else:
print("Awaiting message...")
recieved = client.recv(1024)
recieved = recieved.decode(encoding='utf_8')
print("Message recieved and decoded")
print(recieved)
sd = input('(y/n) >')
if sd == 'y':
print("Closing connection")
client.close()
break
print("Sorry, the server closed the connection!")
這是什麼意思呢?
這基本上是學習和練習套接字編碼。 它應該是一個從服務器向客戶端發送數據的程序,它們都能夠通過回答問題的y或n來終止連接。 如果雙方都繼續回答,程序就會繼續運行。 只要有人回答,它就會終止服務器或客戶端。
現在,我不知道什麼是錯誤的。 如果我爲服務器問題鍵入'y'「您想關閉此連接嗎?」這一切都是應該的。
如果我輸入'n',服務器會做它應該做的事,但客戶端不會收到任何東西。大部分'print'語句都是用於調試的。多數民衆贊成我如何知道服務器工作正常。
那裏有什麼問題?我試圖找到它,但我不能。
我有點新來python和新的套接字編碼。請保持容易。 謝謝。
(我在Win10 CMD批處理腳本運行)(因爲它是流程到流程它可能不叫「服務器」?)