MFC之csocket

来源:互联网 发布:qq输入法linux版 编辑:程序博客网 时间:2024/04/29 04:09

1、一般使用流程(阻塞模式)

1)添加头文件

#include "afxsock.h"

2)初始化

一般在InitInstance()的开始部分增加:

 if (!AfxSocketInit())
 {
  AfxMessageBox("Windows 通信端口初始化失败");
  return FALSE;
 }

3)定义对象

CSocket m_socketRec;

4)发送端:

 if (m_socketListenS.Create(::atoi(sendPort)))
 {
  GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
  
  m_socketListenS.Bind(::atoi(sendPort),sendIp);
  if (m_socketListenS.Listen())
  {
   m_socketListenS.Accept(m_socketSend);
   m_socketListenS.Close();
   static int nIdex = 100;
   CString str;
   str.Format("%010d",nIdex);
   m_socketSend.Send(str,10,0);
         m_edit_send.SetWindowText(str);
   //SetTimer(1,3000,NULL);
  }
 }
 else
 {
  AfxMessageBox("socket创建失败");
  return;
 }

5)接收端

 if (m_socketRec.Create())
 {
  m_socketRec.Connect(recIp,atoi(recPort));
  CString str;
  m_socketRec.Receive((LPVOID)str.GetBuffer(10),10,0);
     m_edit_rec.SetWindowText(str);
  //SetTimer(2,1000,NULL);
 }

原创粉丝点击