views:

282

answers:

2

Hey, I'm doing sockets programming. Pretty much new to it.

The application is a Windows Service, in its ServiceMain() function I call CAsyncSocket's Listen() method, to listen for client connections. But after it starts listening for connections, it'll return and the ServiceMain() function will return and the service is stopped.

What I want to do with this is that, wait until a specific event occurs say WM_QUIT, till than listen for connections. How to do it?

// static member function (callback)
void CNTService::ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
    // m_Server containts two sockets
    // one for listening and one for accepting connections

    m_Server.StartListening(); // calls Listen method on the listener socket

    // it will return and service will quit
    // which I don't want
}

I'm okay with mixing Win32 and MFC, so if it can be done in Win32 please do tell me too :)

A: 

In a service you normally would use WaitForMultipleObjects and wait for whatever things your service does (WSAEventSelect for sockets when not using a framework) + a quit event that you signal when the service manager tells you to quit

Anders
Can you tell me how exactly to wait for the client to connect to the server?Will this work?m_Listener.Listen();WaitForSingleObject(m_Listener);
hab
A: 

The correct way to handle a socket server is something like (pseudo code with winsock) :

bind(listenerSocket);

while(!stopped)
{
     listen(listenerSocket);
     clientSocket = accept(listenerSocket);

     process(clientSocket);
}

The listen call is blocking, waiting for connection. This way you can handle multiple connections. the process method usually spawn a thread in a threadpool.

I'm not familliar with MFC sockets but you have the equivalent things in a more OO way. There is many tutorials about this sort of things. You can also use a library handling sockets (you gain portability ...) like boost.

If you only need to handle a connection and do some process, you only do :

bind(listenerSocket);

listen(listenerSocket);
clientSocket = accept(listenerSocket);

process(clientSocket);
neuro
im using MFCs' sockets
hab
You said that you have no problem with win32. I heard no problem wit winsock ... by the way I give you pseudo code. You can find equivalent calls in MFC socket which are for what i recall OO wrapping around winsock.
neuro
Yea, but if I have to follow your way, I'll have to rewrite everything
hab
I don't know your code but, the idea was to give you the differents steps. I think you have equivalent methods in your MFC sockets. That's why I give you pseudo code and not winsock code. The main point is that after listening you have to accept a connection. then you will get a socket handle that will allow you to receive/send message. anyway, good luck ...
neuro