【问题标题】:I got problems with making a Python socket server receive commands from a Python socket client我在使 Python 套接字服务器从 Python 套接字客户端接收命令时遇到问题
【发布时间】:2015-06-21 19:31:53
【问题描述】:

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

server.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")。

client.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()

【问题讨论】:

    标签: python sockets websocket serversocket


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 2017-04-30
      • 1970-01-01
      • 2021-11-08
      • 2016-07-17
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      相关资源
      最近更新 更多