Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
This is mine program
C++
#define WIN32_LEAN_AND_MEAN
#include <stdlib.h>
#include <stdio.h>
#include <string.h> 
#include <process.h> 
#include<atlstr.h>
#include<Windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std; 
#define DEFAULT_PORT "100"
 class Base
{
public     :    
    struct addrinfo    addr_;   
    unsigned short          port_;      
    CString                  hostname_;    
    CRITICAL_SECTION        sect_;       
    HANDLE                  threadHandle_;    
        HANDLE                  threadHandle1_;  
    bool                    connected_;

public  :       
    SOCKET          sock_; 
    A()
    {

    }


public:
    virtual int ConnectToMachine(void)=0;  //This will make socket connection with the machine.
    virtual int SendRequest(SOCKET sock)=0;      //This will send the request to the machine.
    virtual char* ReceiveResponse(SOCKET sock)=0;  //This will receive the response from the machine that is binary data.

static DWORD WINAPI ServerConnectThread(Base *my);
static UINT ThreadFunc(LPVOID param) ;
static  UINT receive();
static DWORD WINAPI startReceive(LPVOID param){
            Base *_this=(Base*)param;
            _this->receive();
            return 0;
        }
};

 #define DEFAULT_BUFLEN 512
 class Derived :public Base
{
public:
int ConnectToMachine(void)
    {
        int conResult,iResult;
        struct addrinfo           *result = NULL,*ptr = NULL;

        u_long iMode = 0;
        DWORD nTimeout = 5000; // 5 seconds
        int port=22;
        WSADATA wsaData;

        // Initialize Winsock

        iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0) 
        {
            printf("WSAStartup failed with error: %d\n", iResult);

        }

        ZeroMemory( &addr_, sizeof(addr_) );
        addr_.ai_family = AF_UNSPEC;
        addr_.ai_socktype = SOCK_STREAM;
        addr_.ai_protocol = IPPROTO_TCP;

        // Resolve the server address and port
        conResult = getaddrinfo("192.168.1.7", DEFAULT_PORT, &addr_, &result);
        if ( conResult != 0 ) {
            printf("getaddrinfo failed with error: %d\n", conResult);
            WSACleanup();
            return 1;
        }

        // Attempt to connect to an address until one succeeds
        for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

            // Create a SOCKET for connecting to server
            sock_ = socket(ptr->ai_family, ptr->ai_socktype, 
                ptr->ai_protocol);
            if (sock_ == INVALID_SOCKET) {
                printf("socket failed with error: %ld\n", WSAGetLastError());
                WSACleanup();
                return 1;
            }


            conResult = ioctlsocket(sock_, FIONBIO, &iMode);
            if (conResult != NO_ERROR)
                printf("ioctlsocket failed with error: %ld\n", conResult);



            conResult = setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTimeout, sizeof(DWORD));
            if (conResult != NO_ERROR)
            {
                printf("\nSetsocopt fail with error :%d\n",WSAGetLastError());

                return 0;
            }


            // Connect to server.
            conResult = connect(sock_, ptr->ai_addr, (int)ptr->ai_addrlen);
            if (conResult == SOCKET_ERROR) {
                closesocket(sock_);
                sock_ = INVALID_SOCKET;
                continue;
            }
            break;
        }

        freeaddrinfo(result);

        if (sock_ == INVALID_SOCKET) {
            printf("Unable to connect to server!\n");
            WSACleanup();
            return 1;
        }
        DWORD dwThreadId;

            threadHandle_=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc,this,0,&dwThreadId);


    }

    int SendRequest(SOCKET sock)
    {
        int sendResult;
        char data[6]="CM00";
        data[4]=0x0F;
        data[5]=0x0D;
        sendResult = send( sock, data, (int)strlen(data), 0 );
        if (sendResult == SOCKET_ERROR)
        {
            printf("send failed with error: %d\n", WSAGetLastError());
            closesocket(sock);
            WSACleanup();
            return 1;
        }

        printf("Bytes Sent: %ld\n",sendResult);
    }



    char* ReceiveResponse(SOCKET sock )
    {
        int recvResult;
        char recvBuf[1024];
        char common[138];
        int j;
        int w =0;
        int recvbuflen = DEFAULT_BUFLEN;

        do {


            recvResult = recv(sock, recvBuf, recvbuflen, 0);
            if ( recvResult > 0 )
            {   

                //wLog->WriteErrorLog(recvbuf);
                for(j=0;j<=recvResult;j++)
                {
                    common[w] = recvBuf[j];
                    w++;

                }

                printf("Bytes received: %d\n",recvResult);
                memset(recvBuf, 0, sizeof(recvBuf));

            }
            else if ( recvResult == 0 )
                printf("Connection closed\n");
            else
                printf("recv failed with error: %d\n", WSAGetLastError());

        } while( recvResult> 0 );

        return common;
    }

    static UINT Derived::receive(void)
    {
        while(1)
        {
            SendRequest(sock_);
            ReceiveResponse(sock_);
            Sleep(10000);
        }
    }

    DWORD WINAPI Base::ServerConnectThread(LPVOID lpdwThreadParam)
    {
        SOCKET ThreadSocket = INVALID_SOCKET;
        ThreadSocket=(SOCKET)lpdwThreadParam;
        while(1)
        {
            SendRequest(ThreadSocket);
            ReceiveResponse(ThreadSocket);
            Sleep(10000);
        }

    }
     static UINT ThreadFunc(LPVOID param) {   
         Base* obj = (Base*)param;   

         obj->ServerConnectThread(); //how to pass socket
     } 
};

I have to pass the socket that i created in connect function to server connect thread,can you please guide me how to do that
Posted
Comments
Sergey Alexandrovich Kryukov 11-Oct-12 14:10pm    
No, functions cannot be nested, but you can use the power of OOP. What exactly would you want to nest and why?
--SA
Tarun Batra 11-Oct-12 14:13pm    
As you can see the above code in ConnecttoMachine function i want to create a thread and in thread i want to do all sending and receiving can u tell how to do this?
Tarun Batra 11-Oct-12 14:18pm    
Can you please tell sir
Sergey Alexandrovich Kryukov 11-Oct-12 15:38pm    
I think following Marcus's advice in Solution 1 is a good start. Very basically, with TCP, on server side, you would need one extra thread to accept incoming new connections, and one more extra thread to send/receive data to/from all clients in cycle. A client part will need just one extra thread: to connect and to send/receive data. You should clearly define your application level protocol and follow it in both parts. Everything else depends on your application.

There is nothing related to nested function. I think you are just confused.
--SA

I get the idea that you are not too familiar with Threading yet, so I would suggest that this article would be of great use to you in understanding how to approach this issue.
Multithreading Tutorial[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Oct-12 15:35pm    
Something to start with, my 5.
I would add that without multithreading, messing up with sockets, networking, or something similar, would be totally crazy.
--SA
Sergey Alexandrovich Kryukov 11-Oct-12 15:40pm    
I also shared some ideas in my comment to the question and Solution 2, please see.
--SA
Richard MacCutchan 11-Oct-12 17:48pm    
Check OP's other questions and you will see what he is familiar with.
Please see my comment to the question. This past answer can give you the basic ideas:
Multple clients from same port Number[^].

—SA
 
Share this answer
 
you do not need to pass the socket. It is a member variable of the class.
So, all you need to do is to modify the code like this:
C++
DWORD WINAPI Base::ServerConnectThread()
{
    while(1)
    {
        SendRequest(sock_);
        ReceiveResponse(sock_);
        Sleep(10000);
    }
    return 0;

}
 static UINT ThreadFunc(LPVOID param) {
     Base* obj = (Base*)param;

     obj->ServerConnectThread();
     return 0;
 }


You need to change the declaration of the ServerConnectThread() like this (remove static):

C++
 class Base
{
public:
...
DWORD WINAPI ServerConnectThread();
....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900