您的位置:首页 > 理论基础 > 计算机网络

VC6.0下TCP/IP和UDP的简单实现

2013-06-15 15:34 453 查看

#2013 6.15

                    今天刚放假回来不想工作,想想整理下一下节前的东西。当随笔记录下来。

         首先在VC6.0下建立一个基于对话框的程序,在建立对话的时候,在选项页的第二页 在是否带有WInSock编程的选项卡前勾选,把winsock选项选上。

        一. 在BOOL CXXXApp::InitInstance()中写入 下列代码

BOOL CNAVTestApp::InitInstance()
{
//1#
if ( !AfxSocketInit( ) )
{
AfxMessageBox( "Winsock 初始化失败" );
return FALSE;
}
///////一般来说 WASAtarup() 是应用程序调用的windows sockets dll的第一个函数,在调用任何winsock api之前,必须调用wsastartup()进行初始化,最后调用WSACleanup()做清理工作. 也就是 wsastartup 与 wsacleanup 要配对使用.
      MFC中的函数 AfxSocketInit() 包装了函数 WSAStartup(), 在支持WinSock的应用程序的初始化函数IninInstance()中调用AfxSocketInit()进行初始化, 程序则不必调用WSACleanUp().  
      如果你再次调用wsacleanup, 难不定会出问题.
AfxEnableControlContainer();

// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.

#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif

//2#
m_bConnectState = FALSE; // 初始化连接状态为未连接
WSADATA wsd; // 定义WSADATA对象
WSAStartup( MAKEWORD(2,2),&wsd ); // 初始化套接字
//3#
m_LocalSocket = socket( AF_INET, SOCK_STREAM, 0 ); //创建套接字
if ( m_LocalSocket == INVALID_SOCKET )
{
TRACE( "创建套接字失败!\n" );
return FALSE;
}
//4#
unsigned long nCmd; // int ioctlsocket( SOCKET s, long cmd, u_long FAR* argp)
int nState = ioctlsocket( m_LocalSocket, FIONBIO, &nCmd);// argp指向一个无符号长整型。如允许非阻塞模式则非零,如禁止非阻塞模式则为零
if ( nState != 0 )
{
TRACE( "设置套接字非阻塞模式失败" );
}

CNAVTestDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}

// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
           二.接下来在对话框初始化里

//5#
//设置套接字WSAAsyncSelect模型
int nRes = WSAAsyncSelect(theApp.m_LocalSocket,m_hWnd,WM_SOCKET,
FD_ACCEPT|FD_CLOSE|FD_READ|FD_WRITE|FD_CONNECT);
if ( nRes != 0 )
{
TRACE( "设置WSAAsyncSelect模型失败!" );
}
SocketConnect( 2111 );
VOID CNAVTestDlg::SocketConnect(int port)
{
closesocket( theApp.m_LocalSocket ); //先关闭已有的Socket句柄

theApp.m_LocalSocket = socket(AF_INET, SOCK_STREAM, 0);//创建套接字
int nRet = WSAAsyncSelect(theApp.m_LocalSocket,AfxGetMainWnd()->m_hWnd,WM_SOCKET,
FD_ACCEPT|FD_CLOSE|FD_READ|FD_WRITE|FD_CONNECT);

sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons( port );
sockAddr.sin_addr.S_un.S_addr = inet_addr("192.168.1.27");
connect(theApp.m_LocalSocket, (sockaddr*)&sockAddr, sizeof(sockAddr));
theApp.m_bConnectState = FALSE;
}

        三.自己定义消息相应函数声明

       在CXXXTestDlg.h 头文件中添加声明

class CXXXTestDlg : public CDialog
{
// Construction
public:
VOID Sendinfo(CString sendinfo);
LRESULT OnSocket(WPARAM WParam,LPARAM lParam); 消息函数
}
在CXXXTestDlg.cpp 文件中把函数和消息关联起来
BEGIN_MESSAGE_MAP(CNAVTestDlg, CDialog)
//{{AFX_MSG_MAP(CNAVTestDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
ON_BN_CLICKED(IDC_BUTTON4, OnButton4)
ON_BN_CLICKED(IDC_BUTTON5, OnButton5)
ON_BN_CLICKED(IDC_BUTTON6, OnButton6)
ON_BN_CLICKED(IDC_BUTTON7, OnButton7)
ON_WM_TIMER()
ON_BN_CLICKED(IDC_BUTTON8, OnButton8)
ON_BN_CLICKED(IDC_BUTTON9, OnButton9)
//}}AFX_MSG_MAP
ON_MESSAGE(WM_SOCKET,OnSocket) //把消息和函数关联起来
END_MESSAGE_MAP()

      四。下面为消息响应函数

LRESULT CNAVTestDlg::OnSocket(WPARAM WParam, LPARAM lParam)
{
int nEvent = WSAGETSELECTEVENT(lParam);
int nError = WSAGETSELECTERROR(lParam);
CString sRecvData;
char buffer[2048] = {0};
SOCKET sock = WParam;
int nFactLen = recv( sock, buffer, 2048 , 0 );

switch( nEvent )
{
case FD_READ:
break;
case FD_CONNECT:
{
if ( nError == 0 ) //连接成功
{
theApp.m_bConnectState = TRUE;
SetWindowText( "TCP连接成功" );
}
else
SetWindowText( "TCP连接失败" );
}
break;
case FD_CLOSE:
{
theApp.m_bConnectState = FALSE;
}
break;
}
return 0;
}

第一次写博客 我是新手请多指教

          

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: