我有2个模块。我想使用全局变量server
将响应发送到服务器。当我尝试发送数据时,它会显示BROKEN PIPE
,这意味着连接已丢失。因此数据无法发送。它的作用是,在将tcp_driver
导入send_response
文件时,它再次初始化server
变量,因为它保持未连接状态,因此返回BROKEN PIPE错误。
如何使用全局变量server
来发送数据。
PS:我不想将服务器变量作为参数传递。我也不想将服务器变量保存到第3个模块,从而从第3个模块继承它。
以下是我的模块。
tcp_driver.py
import send_response
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
server_address = (config.IP_ADD, config.PORT)
def main():
while True:
try :
server.connect(server_address)
print "Connected"
break
except socket.error: # Tries to connect to the server until it is connected.
print "Not Connected"
continue
response = "Hello Server"
send_response.send_response_to_server(response)
if __name__ == "__main__":
main()
send_response.py
import tcp_driver
def send_response_to_server(response):
try : server.send(response)
except : tcp_driver.main() # if connection is broken, it tries to connect again.