0
$\begingroup$

Rosanswers logo

Hi, I was trying to write a node acting as a tcp server, my first try (to see if evrythin worked) is the following

#include "iostream"
#include "vector"
#include "string"
#include "ros/ros.h"
#include "netinet/in.h"

using namespace std;

int main(int argc, char **argv)
{
  ros::init(argc, argv, "cobot_service_test");
  ros::NodeHandle n;
  
  int sockfd, newsockfd, portno;
  socklen_t clilen;
  char buffer[1024];
  struct sockaddr_in serv_addr, cli_addr;
  int ns;

  sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  bzero((char *) &serv_addr, sizeof(serv_addr));
  portno = 27015;
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);

  if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
  {
      perror("ERROR on binding");
      exit(1);
  }
  
  printf("Starting the server\n");
  listen(sockfd,1);
  clilen = sizeof(cli_addr);
  newsockfd = accept(sockfd, NULL, NULL);

  if (newsockfd < 0)
  {
      perror("ERROR on accept");
      exit(1);
  }
  bzero(buffer,1024);
  
  while(ros::ok())
  {
      ns = recv(newsockfd,buffer,1023, 0);
      if (ns < 0)
      {
          perror("ERROR reading from socket\n");
          exit(1);
      }
      if (ns > 0)
      {
          printf("Message received: %s\n",buffer);
      }
  }

  return 0;
}

This works fine as server the problem is that I cant stop it using ctrl-c (but if i use the same code without ROS I can). I think I'm missing something on how ros::spin works but I really didn't understood how I'm supposed to use it. Thanks a lot for your help!


Originally posted by erpa on ROS Answers with karma: 111 on 2012-04-10

Post score: 1


Original comments

Comment by Mac on 2012-04-10:
...why are you writing a TCP server? The whole point of ROS messages is to let you skip all of that...

Comment by erpa on 2012-04-10:
because i need it to get messages from another pc running windows

Comment by Mac on 2012-04-10:
Ok, good reason. Painful to have to do this by hand, though.

Comment by wdsky2010 on 2015-11-15:
Now I am facing the same problem just like yours, I wonder how did you solve it? Many thanks:-)

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

You might need to add a ros::spinOnce() in your main loop.


Originally posted by joq with karma: 25443 on 2012-04-10

This answer was ACCEPTED on the original site

Post score: 3


Original comments

Comment by erpa on 2012-04-10:
you mean in the while(ros::ok) loop?

Comment by Lorenz on 2012-04-10:
Yes. spinOnce processes all pending ROS events. Alternatively you can use an AsyncSpinner. See here: http://www.ros.org/wiki/roscpp/Overview/Callbacks%20and%20Spinning

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.