简体   繁体   中英

Can't figure out how to implement threads in my client-server model

I have a small server-client application that doesn't do very much (a client connects to the server, sends a number trough a pipe and receives another number).

But it only works with one connection at a time (While a client is connected, no other client has access to the server)

I want to make it possible for multiple clients to connect to the server at one time, and I plan to do this with worker threads.

Obs:

#define CONNECT_NAMEDPIPE "\\\\.\\pipe\\ClientToServer"

Server:

HANDLE namedPipe = CreateNamedPipe (CONNECT_NAMEDPIPE, 
                                    PIPE_ACCESS_DUPLEX,
                                    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                                    2,
                                    sizeof(MinMax),
                                    sizeof(NumberList),
                                    0,                  // timeout
                                    NULL);

if (namedPipe == INVALID_HANDLE_VALUE) {
    printf("Unable to create named pipe\r\nServer closing\r\n");
    printf("CreateNamedPipe failed, GLE=%d.\r\n", GetLastError());
} // Error unable create pipe
else {
    printf("Server created\r\n");
    printf("Awaiting connection\r\n");

    ConnectNamedPipe(namedPipe, NULL);
    etc ...
}

So the server waits on ConnectNamedPipe until a client connects, then is unavailable for any other connections.

If I'd like to enable multiple connections, how should I create the worker threads ?

Should every connection attempt create a new pipe (with a new pipe name / path - CONNECT_NAMEDPIPE can't be used for all)

How do I know when someone else is trying to connect ? Where should my threads be ? I'm stuck.

I think Berkeley sockets are better suited for this. If you must go with pipes, something like this could work:

  1. The client sends a connection request through the main named pipe to the control thread.
  2. The server creates (or fetches from a pool) a worker thread that listens on another, unique pipe.
  3. The control thread answers with the name of this new pipe.
  4. The client closes the control pipe and sends real request data to the new pipe.
  5. The worker thread reads the request, processes it, and sends back the response.
  6. Meanwhile the control thread is ready to read another connection request from another client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM