Queue socket connection in C


Domyō

In a client-server architecture, I have a server that accepts connections from clients. I would like the server to accept 3 simultaneous connections and the remaining connections (if available) will be put on hold to be served FIFO. What is the correct way to do it?

One possible way I can think of is

Create a counter and check if it's less than 3, accept, serve the client in a new thread, then increment the counter. When counter is greater than 3, just accept the socket descriptor and save it in the queue. When one client finishes work, stop the thread (eg by joining a thread) and decrement the counter to allow another client to be serviced. If the queue is not empty, pop a socket descriptor, create a thread and serve the client.

Thanks for your feedback.

Domyō

Due to listena backlog of pending features, ie. It will keep all connections in a queue and when acceptcalled, actually wait for the first element in the queue to be accepted, the solution for this is as follows.

In an infinite loop, connections are only accepted as long as the counter is less than a certain number (the maximum number of clients to serve simultaneously). Declare a mutexcounter that protects the counter, which is incremented each time a connection is accepted. Declare a condition variable to b to signal when the thread has completed its task. Using that condition variable and a mutex, wait if counter is greater than X. After the thread serving the client completes its task, it decrements counter and signals the condition. So the infinite loop will loop again and accept clients already reserved.

A possible implementation could be:

// global variable 
pthread_mutex_t lock;
pthread_cond_t cv;
int number_of_connected_client = 0;

// a function executed by a thread to handle each user
void *client_thread(void *arg) {

  /* some code */

  // thread is about to finish and return
  // client disconnected --> decrement number of connected clients 
  // signal that a client disconnected
  pthread_mutex_lock(&lock);
  number_of_connected_client-- ;
  pthread_cond_signal(&cv);
  pthread_mutex_unlock(&lock);
  return 0;
}

// infinte loop for accepting connections
while (1) {

  // serve 2 users at a time, queue the rest of the clients in the listen's queue 
  if( number_of_connected_client >= 2 ) {
    pthread_mutex_lock(&lock);      
    pthread_cond_wait(&cv, &lock);
    pthread_mutex_unlock(&lock);
  }

  connfd = accept(listenfd, (struct sockaddr *) NULL, NULL );

  // create a thread and serve the client 
  if( pthread_create( &thread_id , NULL , client_thread, (void*)connfd) <0)
    {
     // error in creating thread
     // do something 
    }

  // client is served --> increment number of connected clients 
  else {
    pthread_mutex_lock(&lock);
    number_of_connected_client ++;
    pthread_mutex_unlock(&lock);
  }

}

It's just a simple workaround to enable things to be privately tested or hardware tested, etc. The correct way to handle this is to pool threads and assign the worker threads the task provided by the Inspired annotation.

Related


Queue socket connection in C

Domyō In a client-server architecture, I have a server that accepts connections from clients. I would like the server to accept 3 simultaneous connections and the remaining connections (if available) will be put on hold to be served FIFO. What is the correct w

C: Socket connection and data loss

username I have a client and server that communicate via sockets. I set them like this: sockfd = socket(AF_INET, SOCK_STREAM, 0); ... The client contacts the server and the server sends a response (2906 bytes in my test case): n = write(newsockfd, msgout,strl

C: Socket connection and data loss

username I have a client and server that communicate via sockets. I set them like this: sockfd = socket(AF_INET, SOCK_STREAM, 0); ... The client contacts the server and the server sends a response (2906 bytes in my test case): n = write(newsockfd, msgout,strl

C: Socket connection and data loss

username I have a client and server that communicate via sockets. I set them like this: sockfd = socket(AF_INET, SOCK_STREAM, 0); ... The client contacts the server and the server sends a response (2906 bytes in my test case): n = write(newsockfd, msgout,strl

listen() queue length in socket programming in C?

Grijesh Chauhan: I wrote two pairs of codes ( server.cand client.c) in Linux . One for the UNIX domain and the AF_UNIXother for the INTERNET domain AF_INET. Both work fine! listen()Required Backlog Queue Length = 3 inboth servers listen(sockfd, 3); In UNIX

listen() queue length in socket programming in C?

Grijesh Chauhan: I wrote two pairs of codes ( server.cand client.c) in Linux . One for the UNIX domain and the AF_UNIXother for the INTERNET domain AF_INET. Both work fine! listen()Required Backlog Queue Length = 3 inboth servers listen(sockfd, 3); In UNIX

connection queue

Johnson I ran into this problem in the book Algorithms by Sedgewick and Wayne. A connectable queue, stack or instruction. Adds an additional class of operations that (destructively) connects two queues, stacks or instructions (see exercise 1.3.32). Hint: Use a

connection queue

Johnson I ran into this problem in the book Algorithms by Sedgewick and Wayne. A connectable queue, stack or instruction. Adds an additional class of operations that (destructively) connects two queues, stacks or instructions (see exercise 1.3.32). Hint: Use a

connection queue

Johnson I ran into this problem in the book Algorithms by Sedgewick and Wayne. A connectable queue, stack or instruction. Adds an additional class of operations that (destructively) connects two queues, stacks or instructions (see exercise 1.3.32). Hint: Use a

connection queue

Johnson I ran into this problem in the book Algorithms by Sedgewick and Wayne. A connectable queue, stack or instruction. Adds an additional class of operations that (destructively) connects two queues, stacks or instructions (see exercise 1.3.32). Hint: Use a

C++ socket closed on first connection attempt

Fabiotk : I'm trying to create a server example in c++ using <sys/socket.h>Qt Creator gui builder and Qt Creator , but two strange behaviors are happening with the socket layer of the program. First, I run the server, but the first attempt to connect using the

Socket connection between PHP and C++

skjindal93 I have created TCP socket connection between PHP page and C++ code. Here is the C++ code for this. Server.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netine

C++ socket closed on first connection attempt

Fabiotk : I'm trying to create a server example in c++ using <sys/socket.h>Qt Creator gui builder and Qt Creator , but two strange behaviors are happening with the socket layer of the program. First, I run the server, but the first attempt to connect using the

Socket connection for compiled c.cgi

Ning Qiao On Linux, I want to connect to a demon through a socket in a compiled c.cgi program (cgic) which is listening for incoming socket connections. I know the server is working as it will respond to the "nc" command. Assuming the server is a black box, I

Socket connection between PHP and C++

skjindal93 I have created TCP socket connection between PHP page and C++ code. Here is the C++ code for this. Server.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netine

Connection Error: Simple Socket Programming in C in Ubuntu

plow My teacher provided an example socket program - get datetime from server, but I can't get the program to work well. I run the server on a terminal and then the client on another terminal (using "./client 127.0.0.1") and I get a " connection error ". I've

How to completely destroy a socket connection in C

Harry Henan: I have created a chat client in Linux using sockets and I want to completely break the connection. Here is the relevant part of the code: int sock, connected, bytes_recieved , true = 1, pid; char send_data [1024] , recv_data[1024]; struct s

c localhost refused TCP socket connection

jesus martin belanga I'm trying to create a client/server program in localhost, but the client can't connect to the server and I don't know what I'm doing wrong. I tried to debug the program and all parameters seem to be OK. The server does bind, connect, list

Socket connection between PHP and C++

skjindal93 I have created TCP socket connection between PHP page and C++ code. Here is the C++ code for this. Server.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netine

C++ send vector over socket connection

gdogg371 I'm trying to send a vector over a socket and I'm getting a series of errors that I don't know how to fix. The vector sum is sent over the socket as follows: int code = 52; std::vector<uint8_t> data1 = { 4, 1, 0, 0, 0, 0, static_cast<uint8_t>(224

C# how to establish UDP socket connection

多 多 · (Tordor Yanev ( Unhandled Exception: System.Net.Sockets.SocketException: The attempted operation is not supported by the referenced object type I try to map ip to V6 same exception namespace ConsoleApp1 { using System.Net; using System.Net.Socket

C++ socket closed on first connection attempt

Fabitok I'm trying to create a server example in c++ using <sys/socket.h>Qt Creator gui builder and Qt Creator , but two strange behaviors are happening with the socket layer of the program. First, I run the server, but on the first try I make a connection wit

C++ socket closed on first connection attempt

Fabitok I'm trying to create a server example in c++ using <sys/socket.h>Qt Creator gui builder and Qt Creator , but two strange behaviors are happening with the socket layer of the program. First, I run the server, but on the first try I make a connection wit

C# TCP socket server client connection

Khalid Jarrah Really need your help. My project is to connect two PCs by cable and use tcp socket to send a string in the form of a textbox on the client side to the server. The problem is that I can only send a string and then the connection closes. Client co

Secure socket connection using C++

Dziaji I am trying to get an SSL/TLS connection to work in Windows. Right now, I'm using Schannel, but I'm not sure if this is the correct approach. Here is my code. InitializeSecurityContextA() function throws exception #include "windows.h" #pragma comment(li

Socket connection based on Mac address in C#

Jazinger Ok, so this question comes from my use of Cognex dataman series cameras. In this case, the camera always acts as a server and all devices connected to it act as clients. When we got these cameras, they were always on a weird subnet. For example: 192.1

C socket, the first threaded connection closes the rest

Keyz Clients can connect Contemporary to n pairs of servers. Once the first one succeeds, it must send a signal to all other threads to shut down the remaining threads trying to connect. Do I use joinables threads to do this? If yes, how should I proceed, at l

Socket connection between PHP and C++

skjindal93 I have created TCP socket connection between PHP page and C++ code. Here is the C++ code for this. Server.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netine