我在使 Python 套接字服务器从 Python 套接字客户端接收命令时遇到问题 [英] I got problems with making a Python socket server receive commands from a Python socket client
问题描述
我在使 Python 套接字服务器接收来自 Python 套接字客户端的命令时遇到问题.服务器和客户端可以相互发送文本,但我无法让来自客户端的文本触发服务器上的事件.任何人都可以帮助我吗?我使用的是 Python 3.4.
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()
在 server.py 中,我试图让dodo"这个词触发 print("hejhej")</code>.
In server.py I tried to make the word "dodo" trigger 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()
推荐答案
这里一切正常,但可能不是您想要的方式.如果您在几行上切换顺序,它会在您输入服务器响应之前显示您的事件字符串.
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()
这篇关于我在使 Python 套接字服务器从 Python 套接字客户端接收命令时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!