用CSocket写一个Ping程序,在窗口工程中可以实现,在控制台程序中不能实现,为什么,可以给一个源码吗?         CSocket m_UDPSocket;
BYTE bs1[50]={0x0,0x00,0x0,0x10,0x0,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x20,0x43,0x4b,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x0,0x0,0x21,0x0,0x1};
         if (!AfxSocketInit())
{
AfxMessageBox("Init Fail !");
} if(!m_UDPSocket.Create(5555,SOCK_DGRAM))
{
AfxMessageBox("Failed Create Socket");
} m_UDPSocket.SendTo((void*)bs1,50,137,"200.1.1.1",0);

解决方案 »

  1.   

    应该可以的,把相应的.h文件include
      

  2.   

    不好意思,可以用MFC.
    新建一个代MFC支持的控制台程序,加入Afxsock.h头文件就成了。// Test.cpp : Defines the entry point for the console application.
    //#include "stdafx.h"
    #include "Test.h"
    #include <Afxsock.h>#ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif/////////////////////////////////////////////////////////////////////////////
    // The one and only application objectCWinApp theApp;using namespace std;int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    {
    int nRetCode = 0; // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
    // TODO: change error code to suit your needs
    cerr << _T("Fatal Error: MFC initialization failed") << endl;
    nRetCode = 1;
    }
    else
    {
    // TODO: code your application's behavior here.
    CString strHello;
    strHello.LoadString(IDS_HELLO);
    cout << (LPCTSTR)strHello << endl;
    } CSocket m_UDPSocket;
    BYTE bs1[50]={0x0,0x00,0x0,0x10,0x0,0x1,0x0,0x0,
    0x0,0x0,0x0,0x0,0x20,0x43,0x4b,0x41,
    0x41,0x41,0x41,0x41,0x41,0x41,0x41,
    0x41,0x41,0x41,0x41,0x41,0x41,0x41,
    0x41,0x41,0x41,0x41,0x41,0x41,0x41,
    0x41,0x41,0x41,0x41,0x41,0x41,0x41,
    0x41,0x0,0x0,0x21,0x0,0x1};
        if (!AfxSocketInit())
    {
    cout << (LPCTSTR)"Init Fail !" << endl;
    } if(!m_UDPSocket.Create(5555,SOCK_DGRAM))
    {
      cout << (LPCTSTR)"Failed Create Socket" << endl;
    }
    else
    {
    cout << (LPCTSTR)"Create Socket Success" << endl;
    } m_UDPSocket.SendTo((void*)bs1,50,137,"200.1.1.1",0);
    return nRetCode;
    }
      

  3.   

    我没有说清楚,我已经包含了相应的头文件,并重载了OnRecieve()函数。
    为什么收不到Ping包的回应!
    在窗口程序中可以!
      

  4.   

    你在哪里重载了OnReceive()函数,在CSocket的派生类中吗?
      

  5.   

    我在CSocket的派生类中重载了OnReceive()函数!
      

  6.   

    估计是线程模型的问题。我的一个程序移植到com组件供asp调用的时候也出现这样的问题,后来查证是因为mfc的CSocket线程和我所(期望)使用的方式冲突。后来放弃CSocket,直接socket编程使用阻塞方式就好了。
      

  7.   

    建议采用socket编程使用阻塞方式就好了,不比CSocket复杂多少。
      

  8.   

    CSOCKET内建了一个窗口来处理 FD_READ, FD_WRITE之类的消息, 用于控制台程序, 恐怕...