Jump to content
  • Advertisement
Sign in to follow this  
Terminatore3

accept function stopping app

This topic is 4457 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm sure this is a very obvious question, but I have just started learning about sockets and stuff. When I initialize my sockets on my server I use the accept function to accept any incoming connections. But the problem is I want to be able to stop waiting for more connections if I wanted to, but the accept function seems to freeze the app until it recieves a connection, is there another way of doing this so my app can still run, yet still recieve connections? here's my code to initialize the server
int InitSockets(void)
{
	struct sockaddr *servAddr;
	struct sockaddr_in *inetServAddr;

	int error = 0;

	// Create the socket.
	listeningSocket = socket(AF_INET, SOCK_STREAM, 0);
	printf("Socket\n");

	if(listeningSocket == INVALID_SOCKET)
	{
		printf("error: socket() failed");
		return -1;
	}

	// Allocate memory for the address structure and set it to zero.
	servAddr = (struct sockaddr *) malloc(sizeof(sockaddr));
	memset((char *) servAddr, 0, sizeof(sockaddr));

	// Fill the address structure.
	servAddr->sa_family		= (u_short) AF_INET;
	inetServAddr			= (struct sockaddr_in *) servAddr;
	inetServAddr->sin_port	= htons((u_short) 9009);

	// Bind the address information to the socket.
	error = bind(listeningSocket, servAddr, sizeof(sockaddr));
	printf("bind\n");

	if(error == SOCKET_ERROR)
	{
		printf("error: bind() failed");
		free(servAddr);
		return -1;
	}

	free(servAddr);
	servAddr = NULL;

	// Listen for incoming connections. Queue only one connection.
	error = listen(listeningSocket, 1);
	printf("listen\n");

	if(error == SOCKET_ERROR)
	{
		printf("error: listen() failed");
		return -1;
	}

	// Accept the connection.
	connectedSocket = accept(listeningSocket, NULL, NULL);
	printf("accept\n");

	if(connectedSocket == INVALID_SOCKET)
	{
		printf("error: socket() failed");
		return -1;
	}

	return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
You can use select() to poll for a waiting connection or use ioctlsocket() with FIONBIO to make the socket enter non-blocking mode.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!