Just get one last value from socket

社会主义新天地 提交于 2019-12-13 05:24:32

问题


I send data to socket on one side every second, but I can read that data on another side in any moment. Here's the writer:

from settings import Config

filename = Config.NAVIGATION_SOCKET_FILE

client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
client.settimeout(None)
while True:
    try:
        client.connect(filename)
        break
    except Exception:
        continue
messages = ["$GPRMC,125504.049,A,5542.2389,N,03741.6063,E,0.06,25.82,200906,,,*17",
            "$GPRMC,155604.049,A,5542.2389,N,03741.6063,E,0.06,25.82,200906,,,*19",]
while True:
    msg = random.choice(messages)
    client.send(msg)
    print msg
    time.sleep(1)

And here's reader:

navigation_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
if os.path.exists(app.config['NAVIGATION_SOCKET_FILE']):
        os.remove(app.config['NAVIGATION_SOCKET_FILE'])
navigation_socket.bind(app.config['NAVIGATION_SOCKET_FILE'])

class NavigationInfo(restful.Resource):
    def get(self):
        msg = navigation_socket.recv(1024)
        regex = re.compile(r"^\$GPRMC,(?P<time>\d{6}\.\d{3}),(?P<status>A|V),"
                           r"(?P<latitude>\d{4}\.\d{4}),(?P<lat_n_s>N|S),"
                           r"(?P<longitude>\d{5}\.\d{4}),(?P<long_e_w>E|W),"
                           r"(?P<hor_speed>\d+.\d+),(?P<track_angle>\d+.\d+),"
                           r"(?P<date>\d{6}),(?P<magnetic_declination>\d+\.\d+)?,"
                           r"(?P<magnetic_decl_direction>\d)?,"
                           r"(?P<mode>A|D|E|N)?\*(?P<checksum>\d\d)")
        result = regex.match(msg)
        navigation_info = result.groupdict()
        return navigation_info

So the first problem is that writer just stops writing data to socket when buffer is full (at least that's what I see) and when I request data on the other side, it's too old.

Can just I store one value in buffer and then rewrite it? Or maybe I'm getting it all wrong?


回答1:


I think that you are using the solution in reverse.

Instead of pushing messaging, while not pulling messages ?

Your server may look like:

  1. Wait for a connection
  2. Give a random message
  3. go to step 1

And your client may just connect to the server when he needs a message.

In your case, the connection is "opened all the time", in my solution the socket is opened only when needed. and closed right after the message is delivered.



来源:https://stackoverflow.com/questions/24715082/just-get-one-last-value-from-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!