2
votes

I need to write a sort of proxy server and my design is a little like this: 1. Socket server (using Windows Event select model). program has a listener thread listenimng for network events.
2. list of clients (currently indexed by socketid). 3. socket server accepts a new connection and then creates a new thread for each client. The new thread creates a socket connection to end destination server (want a persistent connection).

I have already written the socket server and that works fine. My problem is as new messages come in from clients, how do I pass this message onto the relevant thread (so message can be sent onto to destination server).

In my server I get the address of the final destination server from the client message. I can lookup the client socket from the list of client sockets. But how do I then send the message to the correct thread?

In the threading I have worked with so far, the thread function just runs a loop. Do I call the thread function, passing it the message as a parameter?

Anyone got any good ideas on how to do this?

Could I not just have a map of client socket id and destination server socket id.

After accept on a client socket, connect to destination server and send msg. Save destination server socket id to the map.

Thenceforth, when get a new msg from client, lookup dest server in map and send message to requisite server socket.

Actually, do I need to make this multi-threaded?

3
Why use sending threads at all? Just have whatever thread receives the client 'message' directly use the outgoing socket. There is otherwise no clean mechanism to switch context to a specific thread without using a queue for each thread.Hans Passant

3 Answers

2
votes

Use a messaging or synchronization primitive, such as a queue, mailbox, event signal, etc.

For instance, if each thread has a queue for data to send, you would simply write to this queue. The queue must be thread safe to allow concurrent access.

1
votes

I am going to make an assumption that each client requires the same processing. So all you need is a bunch of worker threads. Get a connection. Pick up the relevant data (mutex). Process. Fire off the response.

So why a thread for each client. Construct a worker thread when required. Seems a simpler solution.

0
votes

Essentially, you need a message queue for each thread. You can then post the incoming data onto this queue, and the thread can process it in turn.

There are lots of ways of implementing such a queue. You could, for example, use the Windows message queue, and post a Windows message to a window owned by the target thread. Alternatively, you could use a custom thread-safe message queue to pass the data, with the data structure protected by a mutex.