我正在使用sys / socket.h将心跳反复发送到服务器。
连接工作正常。重新启动服务器时发生问题。
这是我的代码。
bool HbClient::start(const char *address, int port)
{
//create socket if it is not already created
if(sock == -1)
{
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket object");
return false;
}
printf("Socket object created\n");
}
server.sin_addr.s_addr = inet_addr( address );
server.sin_family = AF_INET;
server.sin_port = htons( port );
return connect_to_server();
}
bool HbClient::connect_to_server()
{
int status = connect(sock , (struct sockaddr *)&server , sizeof(server));
cout << "returned status: " << status << endl << flush;
if (status < 0)
{
cout << "Error. Connection failed." << endl << flush;
return false;
}
cout << "Connected to server" << endl << flush;
return true;
}
bool HbClient::send_data(const char *data)
{
int res = send(sock , data , strlen(data) , MSG_NOSIGNAL);
if( res < 0)
{
cout << "Data sending failed, status: " << res << endl << flush;
start("127.0.0.1", 9090);
return false;
}
cout << "Data send" << endl << flush;
return true;
}
send_data()函数被重复调用。在服务器重新启动之前,这可以正常工作。但是,当服务器重新启动时,这些输出会重复打印。
Data sending failed, status: -1
returned status: -1
Error. Connection failed.
我正在使用Ubuntu 16.04 OS和g ++编译器。您能指出这里的问题吗?
答案 0 :(得分:1)
在重新连接之前,关闭插座并将其设置为-1。因此,像这样修改send_data
函数:
close(sock);
sock = -1;
start("127.0.0.1", 9090);
套接字函数也总是在失败时返回-1。您应该打印errno
而不是返回的代码