Subscriber to socket in python [closed]

asked 2020-05-27 12:27:49 -0600

Davide gravatar image

Hi everyone I would like to implement a python node that subscribes to a topic (odom in my case) and retransmits part of the message on a socket. I have already implemented such a thing:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import socket
import sys
from nav_msgs.msg import Odometry
import struct
from time import sleep

def callback(msg):
    string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
    try:
        connOdom.send(string.encode())
        print (string)
    except socket.error:
        print ("Error client lost")
        sleep( 2 )

def listener():
    rospy.init_node('serverOdom', anonymous=True)
    rospy.Subscriber('odom',Odometry, callback)
    rospy.spin()

if __name__ == '__main__':
    serverOdom = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        serverOdom.bind(('', 5005))
    except socket.error as msg:
        print('# Bind failed. ')
        sys.exit()
    serverOdom.listen(10)
    connOdom, addrOdom = serverOdom.accept()
    listener()

the problem is that when the client is closed it can no longer reestablish the connection once it has restarted. and i don't know how to fix this. does anyone have any idea? Thanks in advance

edit retag flag offensive reopen merge delete

Closed for the following reason question is off-topic or not relevant. Please see http://wiki.ros.org/Support for more details. by gvdhoorn
close date 2020-05-27 14:07:04.901467

Comments

when the client is closed it can no longer reestablish the connection once it has restarted

if with "client" you are referring to the socket -- so not the ROS side -- then this would not be a ROS problem and I would recommend to not limit yourself to support resources which are ROS specific.

As-is, this reads like a generic Python socket issue, which I would recommend you post about on Stack Overflow or another forum dedicated to such topics.

gvdhoorn gravatar image gvdhoorn  ( 2020-05-27 12:39:15 -0600 )edit

Ok, I was in doubt as to whether to ask here or on another forum. thanks

Davide gravatar image Davide  ( 2020-05-27 13:28:58 -0600 )edit