masesk/easy-socket

socketConnect() exception handling issue

Closed this issue · 1 comments

I'm testing a simple client call.

To test the exception, I call socketConnect() without an actual server to connect to.

But in my try/catch I am not able to catch the socket_error_exception. My code:

try
{
	client->socketConnect("io_update", "127.0.0.1", 50051);
}
catch(const masesk::socket_error_exception& e)
{
	return -3;
}

will just terminate the program, without catching anything.

I looked at your code:

void socketConnect(const std::string &channelName, const std::string &ip, std::uint16_t port)
{
	if (sockInit() != 0)
	{
		throw masesk::socket_error_exception();
		return;
	}
	SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == INVALID_SOCKET || sock == SOCKET_ERROR)
	{
		sockQuit();
		throw masesk::socket_error_exception();
	}
	sockaddr_in hint;
	hint.sin_family = AF_INET;
	hint.sin_port = htons(port);
	inet_pton(AF_INET, ip.c_str(), &hint.sin_addr);
	int connResult = connect(sock, (sockaddr *)&hint, sizeof(hint));
	if (connResult == SOCKET_ERROR)
	{
		sockClose(sock);
		sockQuit();
		throw socket_error_exception();
	}
 ...

and noticed that sockQuit() will actually return 0 before the throw. Would that be a problem?

Thanks

I actually tested using the /test/test-client/Client.cpp.

I modified it to catch the exception:

#include <iostream>
#include <masesk/EasySocket.hpp>
#include <string>
using namespace std;
using namespace masesk;

int main() {
	EasySocket socketManager;
	try
	{
		socketManager.socketConnect("test", "127.0.0.1", 8080);
		string userInput;
		while (true) {
			cout << "> ";
			getline(cin, userInput);
			if (userInput.size() <= 0) {
				break;
			}
			socketManager.socketSend("test", userInput);
		}
		socketManager.closeConnection("test");
	}
	catch(const socket_error_exception& e)
	{
		std::cerr << "Could not find server endpoint: " << e.what() << '\n';
	}
	
	
	return 0;
}

and everything works as expected. Therefore, the problem was on my side, not on the library.