Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. dialog based MFC multithreaded server

dialog based MFC multithreaded server

Scheduled Pinned Locked Moved C / C++ / MFC
c++designsysadmintutorialquestion
10 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Manmohan29
    wrote on last edited by
    #1

    I am writing a multithreaded TCP server(MFC). The steps I am following are:- 1.)Create a listen socket. 2.)listen on specific port. 3.)spin individual thread for every client that connects. My application is a dialog based MFC App.But it crashes when a client connects to it. :( While spinning the THREAD what parameter should I pass to the thread's main function(CDialog Object or listening socket).:confused: what type of thread should I Create WORKER or UI. My code is like this:-

    // sockDlg.cpp : implementation file

    BOOL CsockDlg::OnInitDialog()
    {
    .
    .
    .
    // TODO: Add extra initialization here
    int m_iPort = 4000;

    m\_sConnectSocket.SetParent(this);      // Object of CMySocket derived from CAsyncSocket
    m\_sListenSocket.SetParent(this);       // // Object of CMySocket derived from CAsyncSocket
    
    m\_sListenSocket.Create(m\_iPort);
    m\_sListenSocket.Listen();
    
    return TRUE;  // return TRUE  unless you set the focus to a control
    

    }

    void CsockDlg::OnAccept(void)
    {
    //m_sListenSocket.Accept(m_sConnectSocket);
    AfxBeginThread(ThreadServer, this);
    }

    UINT CsockDlg::ThreadServer(LPVOID pParam)
    {
    CsockDlg* C = (CsockDlg*)pParam;
    CAsyncSocket client;
    C->m_sListenSocket.Accept(client);
    //::Sleep(60000);
    return 0;
    }

    I have seen many examples for console servers but how to implement it on a Dialog Based Application?????

    Future Lies in Present. Manmohan Bishnoi

    M 1 Reply Last reply
    0
    • M Manmohan29

      I am writing a multithreaded TCP server(MFC). The steps I am following are:- 1.)Create a listen socket. 2.)listen on specific port. 3.)spin individual thread for every client that connects. My application is a dialog based MFC App.But it crashes when a client connects to it. :( While spinning the THREAD what parameter should I pass to the thread's main function(CDialog Object or listening socket).:confused: what type of thread should I Create WORKER or UI. My code is like this:-

      // sockDlg.cpp : implementation file

      BOOL CsockDlg::OnInitDialog()
      {
      .
      .
      .
      // TODO: Add extra initialization here
      int m_iPort = 4000;

      m\_sConnectSocket.SetParent(this);      // Object of CMySocket derived from CAsyncSocket
      m\_sListenSocket.SetParent(this);       // // Object of CMySocket derived from CAsyncSocket
      
      m\_sListenSocket.Create(m\_iPort);
      m\_sListenSocket.Listen();
      
      return TRUE;  // return TRUE  unless you set the focus to a control
      

      }

      void CsockDlg::OnAccept(void)
      {
      //m_sListenSocket.Accept(m_sConnectSocket);
      AfxBeginThread(ThreadServer, this);
      }

      UINT CsockDlg::ThreadServer(LPVOID pParam)
      {
      CsockDlg* C = (CsockDlg*)pParam;
      CAsyncSocket client;
      C->m_sListenSocket.Accept(client);
      //::Sleep(60000);
      return 0;
      }

      I have seen many examples for console servers but how to implement it on a Dialog Based Application?????

      Future Lies in Present. Manmohan Bishnoi

      M Offline
      M Offline
      Moak
      wrote on last edited by
      #2

      Manmohan29 wrote:

      My application is a dialog based MFC App.But it crashes when a client connects to it.Frown While spinning the THREAD what parameter should I pass to the thread's main function(CDialog Object or listening socket).Confused

      Hi again! 1) CAsyncSocket is event based and there is no need to use multithreading. This kind of networking model provides everything in a single thread context. 2) Did you try an example from the links I gave you a day ago? I would be much easier for us to help when you start from a working example. 3) What do you mean with "spinning a thread"? Happy coding /M

      Webchat in Europe :java: (only 4K)

      M 1 Reply Last reply
      0
      • M Moak

        Manmohan29 wrote:

        My application is a dialog based MFC App.But it crashes when a client connects to it.Frown While spinning the THREAD what parameter should I pass to the thread's main function(CDialog Object or listening socket).Confused

        Hi again! 1) CAsyncSocket is event based and there is no need to use multithreading. This kind of networking model provides everything in a single thread context. 2) Did you try an example from the links I gave you a day ago? I would be much easier for us to help when you start from a working example. 3) What do you mean with "spinning a thread"? Happy coding /M

        Webchat in Europe :java: (only 4K)

        M Offline
        M Offline
        Manmohan29
        wrote on last edited by
        #3

        Thanks for the advice. I was becoming a little bit lazy to search the examples(Today is Diwali[Indian Festival]). But now i will look them. I meant "creating a thread for every client" for "spinning a thread".

        Future Lies in Present. Manmohan Bishnoi

        M 1 Reply Last reply
        0
        • M Manmohan29

          Thanks for the advice. I was becoming a little bit lazy to search the examples(Today is Diwali[Indian Festival]). But now i will look them. I meant "creating a thread for every client" for "spinning a thread".

          Future Lies in Present. Manmohan Bishnoi

          M Offline
          M Offline
          Manmohan29
          wrote on last edited by
          #4

          This is the code for threaded server's accepting function

          void AcceptConnections(SOCKET ListeningSocket)
          {
          sockaddr_in sinRemote;
          int nAddrSize = sizeof(sinRemote);

          while (1) {
              SOCKET sd = accept(ListeningSocket, (sockaddr\*)&sinRemote,
                      &nAddrSize);
              if (sd != INVALID\_SOCKET) {
                  cout << "Accepted connection from " <<
                          inet\_ntoa(sinRemote.sin\_addr) << ":" <<
                          ntohs(sinRemote.sin\_port) << "." <<
                          endl;
          
                  DWORD nThreadID;
                  CreateThread(0, 0, EchoHandler, (void\*)sd, 0, &nThreadID);
              }
              else {
                  cerr << WSAGetLastErrorMessage("accept() failed") << 
                          endl;
                  return;
              }
          }
          

          }

          we accepting the connection

          SOCKET sd = accept(ListeningSocket, (sockaddr*)&sinRemote,
          &nAddrSize);

          and, then creating a thread to handle client

          CreateThread(0, 0, EchoHandler, (void*)sd, 0, &nThreadID);

          Here we are passing the connecting socket to the thread function. And I am puzzled how to pass the connecting socket to thread's function in my application.

          " Future Lies in Present. " Manmohan Bishnoi

          R 1 Reply Last reply
          0
          • M Manmohan29

            This is the code for threaded server's accepting function

            void AcceptConnections(SOCKET ListeningSocket)
            {
            sockaddr_in sinRemote;
            int nAddrSize = sizeof(sinRemote);

            while (1) {
                SOCKET sd = accept(ListeningSocket, (sockaddr\*)&sinRemote,
                        &nAddrSize);
                if (sd != INVALID\_SOCKET) {
                    cout << "Accepted connection from " <<
                            inet\_ntoa(sinRemote.sin\_addr) << ":" <<
                            ntohs(sinRemote.sin\_port) << "." <<
                            endl;
            
                    DWORD nThreadID;
                    CreateThread(0, 0, EchoHandler, (void\*)sd, 0, &nThreadID);
                }
                else {
                    cerr << WSAGetLastErrorMessage("accept() failed") << 
                            endl;
                    return;
                }
            }
            

            }

            we accepting the connection

            SOCKET sd = accept(ListeningSocket, (sockaddr*)&sinRemote,
            &nAddrSize);

            and, then creating a thread to handle client

            CreateThread(0, 0, EchoHandler, (void*)sd, 0, &nThreadID);

            Here we are passing the connecting socket to the thread function. And I am puzzled how to pass the connecting socket to thread's function in my application.

            " Future Lies in Present. " Manmohan Bishnoi

            R Offline
            R Offline
            Rajesh R Subramanian
            wrote on last edited by
            #5

            1. Your first post shows that you're using MFC. You could so use CAsyncSocket like the other poster suggested to you. 2. Creating a thread for each connection is inefficient, and can you imagine what would happen when the number of connections keep raising? If you would like to use threads to serve the client requests, just accept the connections in the UI thread and use a thread pool for the serving purpose. 3. Using CreateThread in an MFC program is an extremely bad idea. If you are using MFC, you *must* use AfxBeginThread to create a worker thread. (Generally there is no reason to call CreateThread at all. If you are not using MFC, you should still be calling _beginthreadex) 4. It looks like you are deriving a dialog class from a socket class? Can't a socket class be contained within your dialog class instead?

            “Follow your bliss.” – Joseph Campbell

            M 1 Reply Last reply
            0
            • R Rajesh R Subramanian

              1. Your first post shows that you're using MFC. You could so use CAsyncSocket like the other poster suggested to you. 2. Creating a thread for each connection is inefficient, and can you imagine what would happen when the number of connections keep raising? If you would like to use threads to serve the client requests, just accept the connections in the UI thread and use a thread pool for the serving purpose. 3. Using CreateThread in an MFC program is an extremely bad idea. If you are using MFC, you *must* use AfxBeginThread to create a worker thread. (Generally there is no reason to call CreateThread at all. If you are not using MFC, you should still be calling _beginthreadex) 4. It looks like you are deriving a dialog class from a socket class? Can't a socket class be contained within your dialog class instead?

              “Follow your bliss.” – Joseph Campbell

              M Offline
              M Offline
              Moak
              wrote on last edited by
              #6

              Just a comment, Rajesh: The poster showed in his previous post that CsockDlg is a CDialog derived class. He tries to convert a multithreaded-socket-API example into an even-based-CAsyncSocket version, if I am not mistaken. Because those two networking models are very different, it's probably easier to start with a fresh working MFC example. :) Cheers /M

              Webchat in Europe :java: (only 4K)

              M 1 Reply Last reply
              0
              • M Moak

                Just a comment, Rajesh: The poster showed in his previous post that CsockDlg is a CDialog derived class. He tries to convert a multithreaded-socket-API example into an even-based-CAsyncSocket version, if I am not mistaken. Because those two networking models are very different, it's probably easier to start with a fresh working MFC example. :) Cheers /M

                Webchat in Europe :java: (only 4K)

                M Offline
                M Offline
                Manmohan29
                wrote on last edited by
                #7

                Here's an excellent tutorial for what I was looking. Please have a look. http://www.flounder.com/kb192570.htm[^]

                Future Lies in Present. Manmohan Bishnoi

                R M 2 Replies Last reply
                0
                • M Manmohan29

                  Here's an excellent tutorial for what I was looking. Please have a look. http://www.flounder.com/kb192570.htm[^]

                  Future Lies in Present. Manmohan Bishnoi

                  R Offline
                  R Offline
                  Rajesh R Subramanian
                  wrote on last edited by
                  #8

                  I'm glad you found something that'd be of use to you. Dr. Joseph is a terrific guy and his site is loaded with useful articles. On an additional note, he is supporting my view of using a thread pool: Even if the message that comes in from the socket requires considerable computing, the more effective method is to have all the sockets running in the main GUI thread, and have the extensive computing handled by threads from a thread pool. Important: Never delete any of your messages that you post to this board. It is a RULE! Read the guidelines. I find a question has been posted to me and come here to reply, but I see that it has been removed.

                  “Follow your bliss.” – Joseph Campbell

                  M 1 Reply Last reply
                  0
                  • R Rajesh R Subramanian

                    I'm glad you found something that'd be of use to you. Dr. Joseph is a terrific guy and his site is loaded with useful articles. On an additional note, he is supporting my view of using a thread pool: Even if the message that comes in from the socket requires considerable computing, the more effective method is to have all the sockets running in the main GUI thread, and have the extensive computing handled by threads from a thread pool. Important: Never delete any of your messages that you post to this board. It is a RULE! Read the guidelines. I find a question has been posted to me and come here to reply, but I see that it has been removed.

                    “Follow your bliss.” – Joseph Campbell

                    M Offline
                    M Offline
                    Manmohan29
                    wrote on last edited by
                    #9

                    I didn't deleted my post intentionally. Just hit the Post Message Button in a hurry instead of preview. Don't misunderstand me.

                    Future Lies in Present. Manmohan Bishnoi

                    1 Reply Last reply
                    0
                    • M Manmohan29

                      Here's an excellent tutorial for what I was looking. Please have a look. http://www.flounder.com/kb192570.htm[^]

                      Future Lies in Present. Manmohan Bishnoi

                      M Offline
                      M Offline
                      Moak
                      wrote on last edited by
                      #10

                      This isn't a simple example and the use of threads together with CAsyncSocket is unjustified and inefficient. Joseph M. Newcomer is a deeply respect member in developer circles, however I would say that the link you found was never intended as a MFC networking tutorial. Mixing asynchronous sockets and threads make little sense, here is an overview of basic server concepts: a) blocking servers (handling only one request at a time, then wait again blocking) b) threaded servers (handling simultaneous requests, one thread for every new socket, maybe from a pool). c) asynchronous server (handling simultaneous requests, one thread context will handle all sockets) d) variants such as IO completition ports Instead of trying to convert one example code you had into a different thing, it would be easier if you learn about different networking concepts and start with simple examples. There are so many choices and CAsyncSocket might not be the best alternative in the long term (there are known problems). Perhaps have a look at some of the links I gave you. :) /M

                      Webchat in Europe :java: (only 4K)

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups