我有一个TCP客户端 - 服务器,其中客户端向服务器发送shell命令,服务器使用所述命令的输出进行响应。某些命令(如 date 或 cd)不起作用,因为它们是交互式的,我假设我的代码不处理它。每当我发送上述命令时,我的客户端似乎都挂起了,只是说发送...我的服务器从未收到任何东西。
我想弄清楚如何处理这种情况,如果发送命令需要超过5秒的时间,客户端将导致超时,或者只是处理它并打印一条消息,指出命令未成功执行,同时保持客户端连接到服务器。
这是我的代码
客户:
import socket
# Client
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creates TCP Socket
# local host and port
LOCAL_HOST = '127.0.0.1'
PORT = 5313
BUFFER_SIZE = 5000 # size of message
sock.settimeout(5)
# connect socket to ip and port
sock.connect((LOCAL_HOST, PORT))
print("Connected to server\n")
print("Enter quit to close connection\n")
while True:
message = input("Please enter a command:\n") # ask user to input message
if message == 'quit':
break
if len(message) == 0:
print("Please enter something")
message = input("Please enter a command:\n")
print("Sending %s" % message)
sock.send(str.encode(message)) # send message
command = str(sock.recv(BUFFER_SIZE), "utf-8") # receive message
print("received %s" % command)
print("closing connection with server")
sock.close()
服务器:
import socket
import subprocess
# Server
# Some commands do not work such as cd. Date does not work on windows because it is interactive.
# creates TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
# port and server ip(localhost)
LOCAL_HOST = ''
PORT = 5313
BUFFER_SIZE = 5000 # size of message
# test connection
print("Server starting up on %s with port number %s" % (LOCAL_HOST, PORT))
# bind socket to ip and port
sock.bind((LOCAL_HOST, PORT))
# listen to socket
sock.listen(1)
繁星coding
相关分类