I got problems with making a Python socket server receive commands from a Python socket client

南楼画角 提交于 2019-12-25 05:35:15

问题


I got problems with making a Python socket server receive commands from a Python socket client. The server and client can send text to each other but I can't make text from the client trigger an event on the server. Could any one help me? I'm using 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()

In server.py I tried to make the word "dodo" trigger 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()

回答1:


Everything here works fine but, maybe not the way you want it to. If you switch the order on a couple of the lines it will display your event string before you enter your server response.

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


来源:https://stackoverflow.com/questions/30968504/i-got-problems-with-making-a-python-socket-server-receive-commands-from-a-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!