I have a server side on my raspberry pi written on C++. I have all sockets logic in another thread, so it should not affect to my main thread. Here is the Servers.hpp:
#pragma once
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <thread>
#include <chrono>
using namespace std;
#define S_OUT_PORT 63253
class TestServer
{
public:
static void Start();
private:
static bool threadIsRunning;
static void LoopOut();
};
Here is the .cpp file:
#include <Servers.hpp>
bool TestServer::threadIsRunning = true;
void TestServer::Start()
{
threadIsRunning = true;
thread th(LoopOut);
th.detach();
}
void TestServer::LoopOut()
{
try
{
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
// logging
return;
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
// logging
return;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(S_OUT_PORT);
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0)
{
// logging
return;
}
if (listen(server_fd, 3) < 0)
{
// logging
return;
}
if ((new_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0)
{
// logging
return;
}
cout << "SC got connection" << endl;
while (true)
{
//SendString(new_socket, "null:null", 9);
int strLen = 9;
string str = "null:null";
char b[4] = { (strLen & 0xff), ((strLen >> 8) & 0xff), ((strLen >> 16) & 0xff), ((strLen >> 24) & 0xff) };
const char* p = reinterpret_cast<const char*>(b);
send(new_socket, p, 4, 0);
send(new_socket, str.c_str(), strLen, 0);
this_thread::sleep_for(chrono::milliseconds(20));
}
}
catch (const std::exception& e)
{
cout << "SC error" << endl;
}
cout << "SC thread exited" << endl;
}
And I start this server just calling TestServer::Start()
in main:
int main()
{
try
{
TestServer::Start();
while (true)
{
cout << "Test" << endl;
this_thread::sleep_for(chrono::milliseconds(3000));
}
}
catch (const std::exception& e)
{
cout << "Main error" << endl;
}
return 0;
}
Then when I'm trying to connect to the server from my pc using C# everything is ok. But when I close the socket from C# side, C++ just terminates. Here is how I shut down connection on C# side:
sct.Shutdown(SocketShutdown.Both);
sct.Close();
What could be the reason of this? Why does socket's shutdown and close kill my main thread in C++?
EDIT 1: Here is the output on the server side:
Test
Test
Test
SC got connection
Test
pi@raspberrypi:~/picadCpp/build $
And the loop in LoopOut
method removed, but result is the same...