您的位置:首页 > 其它

2.使用MFC的CSocket类建立简单的UDP通信

2017-06-05 16:30 489 查看
接收端:

// csocketReceive.cpp : 定义控制台应用程序的入口点。
//
//接收端 右键项目属性 MFC的使用改成共享 dll.

#include "stdafx.h"
#include <afxsock.h>
using namespace std;
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
AfxSocketInit();
CSocket sock;
bool b = sock.Create(8888, SOCK_DGRAM);//socket bind绑定端口
if (!b)
{
cout << GetLastError() << endl;
return -1;
}
char s[2048];
int n = 0;
CString szIP;
UINT nPort;
while ((n = sock.Receive(s,sizeof(s))) > 0)
{
if (s[0] == '#')
break;
cout << "IP是:" << (LPCTSTR)szIP << "端口是:" << nPort << endl;
s
= 0;
cout << s << endl;
}
return 0;
}


发送端:

// csocket.cpp : 定义控制台应用程序的入口点。
//
//发送端 右键项目属性 MFC的使用改成共享dll mfc
//使用MFC的CSocket类实现UDP通信
#include "stdafx.h"
#include <afxsock.h>
using namespace std;
#include <iostream>

int _tmain(int argc,_TCHAR* argv[])
{
AfxSocketInit();
CSocket sock;
BOOL b = sock.Create(0,SOCK_DGRAM);//绑定自己的端口
if (!b)
{
cout << GetLastError() << endl;
}
char s[2048];
while (true)
{
cin >> s;
sock.SendTo(s, strlen(s), 8888, _T("192.168.1.1"));//接收的端口和IP地址 _T()表示Unicode的意思
if(s[0] == '#')
break;

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