-6

这是我的程序

#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
     } 
};

我必须将我在连接函数中创建的套接字传递给服务器连接线程,你能指导我怎么做吗

4

1 回答 1

2

TL;博士

使用成员变量:

class Base
{
    ...
public:
    int the_socket_that_i_created_in_connect_function;
};
于 2012-10-11T18:15:21.780 回答