2016-08-20 61 views
0

我正在尝试学习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批处理脚本运行)(因为它是流程到流程它可能不叫“服务器”?)

回答

0

在你代码中的每个connect应该有一个匹配accept在服务器端。
您的客户端connect一度每个会话, 但服务器accept s各自消息后,因此在其中第二recv调用服务器已经在试图接受其他客户端的位置。 显然,你的服务器应该只处理一个客户端, 所以你可以移动呼叫accept圈外:

s.listen(5) 
(client, address) = s.accept() 
print(address, 'just connected!') 

while True: 
    message = raw_input("Would you like to close the connection? (y/n)") 
相关问题