我在让Python套接字服务器接收来自Python套接字客户端的命令时遇到了问题



我在让Python套接字服务器接收来自Python套接字客户端的命令时遇到了问题。服务器和客户端可以互相发送文本,但我不能让客户端的文本触发服务器上的事件。有人能帮我吗?我使用的是Python 3.4。

服务器.py

import socket 
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host, port)) 
s.listen(1) 
conn, addr = s.accept() 
print ("Connection from", addr) 
while True: 
    databytes = conn.recv(1024)
    if not databytes: break
    data = databytes.decode('utf-8')
    print("Recieved: "+(data))
    response = input("Reply: ")
    if data == "dodo":
        print("hejhej")
    if response == "exit": 
        break
    conn.sendall(response.encode('utf-8')) 
conn.close()

在server.py中,我试图让单词"dodo"触发print("hejhej")

客户.py

import socket 
host = '127.0.0.1'
port = 1010 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((host, port)) 
print("Connected to "+(host)+" on port "+str(port)) 
initialMessage = input("Send: ") 
s.sendall(initialMessage.encode('utf-8'))  
while True: 
 data = s.recv(1024) 
 print("Recieved: "+(data.decode('utf-8')))
 response = input("Reply: ") 
 if response == "exit": 
     break
 s.sendall(response.encode('utf-8')) 
s.close()

这里的一切都很好,但可能不是你想要的方式。如果你在几行上切换顺序,它会在你输入服务器响应之前显示你的事件字符串。

import socket 
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host, port)) 
s.listen(1) 
conn, addr = s.accept() 
print ("Connection from", addr) 
while True: 
    databytes = conn.recv(1024)
    if not databytes: break
    data = databytes.decode('utf-8')
    print("Recieved: "+(data))
    if data == "dodo":  # moved to before the `input` call
        print("hejhej")
    response = input("Reply: ")
    if response == "exit": 
        break
    conn.sendall(response.encode('utf-8')) 
conn.close()

相关内容

  • 没有找到相关文章

最新更新