最后从套接字获取一个值
我每秒钟在一边发送数据到套接字,但在另一边我可以随时读取这些数据。这里是发送数据的代码:
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)
这是接收数据的代码:
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
所以第一个问题是,当缓冲区满的时候,发送数据的部分就停止写入数据到套接字(至少这是我看到的情况),而当我在另一边请求数据时,得到的数据已经太旧了。
我能不能只在缓冲区里存一个值,然后再写入新的值?还是说我理解错了什么?
1 个回答
0
我觉得你可能是把解决方案搞反了。
你是想推送消息,但却没有拉取消息,对吧?
你的服务器可能是这样的:
- 等待连接
- 发送一条随机消息
- 回到第一步
而你的客户端可能只是需要消息的时候才连接到服务器。
在你的情况下,连接是“一直打开着”的,而在我的方案中,连接只有在需要的时候才打开,并且在消息发送完后立刻关闭。