简体   繁体   中英

Publishing data via socket after connection is aborted

I have a Python (2.7) script which is reading realtime data from a file and publishing it (via network) to a server living on a different computer. This server, in particular, is a Carbon server part of graphite .

The relevant part of the code is as follows:

import socket

CARBON_HOST = 'COMPUTER-NAME'
CARBON-PORT = 2003
CARBON_PATH = 'folder.name.meaurement'

s = socket.socket()
s.connect((CARBON_HOST, CARBON_PORT))

while True:
 if s:
  s.send('%s %s %s\n'%(CARBON_PATH, str(data), int(time.time())))
    time.sleep(WAIT)

where data is the latest entry imported from my file, and time is the usual.

When I switch off the computer COMPUTER-NAME where the Carbon server lives, this error appears:

s.send('%s %s %s\\n'%(CARBON_PATH, str(data), int(time.time())))
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine

When I restart the host machine ( COMPUTER-NAME ), I have to restart the Python script for data to be sent over again.

Is there a way I can tell the socket to pause if it sees it's disconnected, or to keep trying until the connection is open again?

I recommend to read about socket.timeout("seconds to sleep") which will give you idea of using it. In your case, use socket.settimeout() right before making a socket connection, and socket.settimeout(None) soon after socket.connection(). In this way, you can delay establishing connection. But if timeout value goes beyond system/server down time, then script will eventually come out with same timeout error.

connect_timeout = 100 #in seconds
socket.settimeout(connect_timeout)
socket.connect()
socket.settimeout(None)

Check if that works?

You can't use the same socket after a socket.error exception, the connection is broken. However, you can catch the exception, create a new connection, and use that to send the data.

About your last question, you can tell your program to keep trying until the data is sent with a while loop. A basic example,

import socket
import time

CARBON_HOST = 'COMPUTER-NAME'
CARBON_PORT = 2003
CARBON_PATH = 'folder.name.meaurement'
WAIT = 10

s = socket.socket()
s.connect((CARBON_HOST, CARBON_PORT))
data = 'my data'

while True:
    packet = '%s %s %s'%(CARBON_PATH, str(data), int(time.time()))
    while True:
        try:
            s.send(packet)
            break
        except socket.error as e:
            print(e)
            s.close()
            s = socket.socket()
            s.connect_ex((CARBON_HOST, CARBON_PORT))
    time.sleep(WAIT)

s.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM