我有一个客户端和服务器计算机。
我从客户端发送了一个Linux命令,该命令在80秒后回复。 由于服务器未在最初的80秒内回复,因此(s.recv)发生了超时错误。
请帮助此处进行操作?
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(300)
s.connect((hostname, self.port))
s.sendall(self.msg)) # where msg is some linux command or script which replies after 80 seconds
#s.shutdown(socket.SHUT_WR)
while 1:
data = s.recv(1024)
if data == b"":
break
datai = datai + data.decode()
self.result[hostname.decode()] = datai
答案 0 :(得分:0)
我无法复制它。这几乎是您拥有的服务器和客户端代码-可以按需工作:
客户端:
#!/usr/bin/env python3
import socket #for sockets
import sys #for exit
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
print 'Socket Created'
host = 'localhost'
port = 8888
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
message = "The message \n"
#Code from Stackoverflow question
#s= socket.socket(socket.AF_INET, socket.SOCK_STREAM) # this is already done
s.settimeout(300)
#Connect to remote server
#s.connect((hostname, self.port)) # different variable name
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
s.sendall(message) # where msg is some linux command or script which replies after 80 seconds
#s.shutdown(socket.SHUT_WR)
while 1:
data = s.recv(1024)
print("Ok, I get the response :)")
if data == b"":
break
datai = "DATAI: "
datai = datai + data.decode()
#self.result[hostname.decode()] = datai
print("Datai: " + str(datai))
#End
break
s.close()
服务器:
#!/usr/bin/env python3
'''
Simple socket server using threads.
Taken from: https://www.binarytides.com/python-socket-server-code-example/
'''
#Code for reproduce stackoverflow question
from time import sleep
#End
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
while True:
#Receiving from client
data = conn.recv(1024)
#Code for reproduce stackoverflow question
print("Waiting 80secs...")
sec = 0
while(sec < 80):
sleep(10)
sec = sec + 10
print(str(sec))
print("Ok, I'll reply...")
#End
if not data:
reply = ""
else:
reply = 'OK...' + data
conn.sendall(reply)
break
conn.close()
s.close()