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:-)