注意:
1、UDP发送和接受数据分别使用sendto()和recvfrom()函数,注意函数的用法;
2、在VisualStudio2015中关于绑定本地Ip地址的inet_addr()函数在c++11中和以前的版本有所区别;
3、TCP通信和UDP通信的流程非常相似,但多了”握手”的过程;
4、简单通信的实现具有一定的逻辑。
Client端:
#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <string>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main() {
//初始化WinSock库;
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsadata;
if (WSAStartup(sockVersion,&wsadata)!=0)
{
printf("WinSock2 initalise failed!");
return 0;
}
/*const char* strptr = "192.168.0.105";
void* addptr=nullptr;*/
/*创建套接字,设置相关参数,本地ip地址和端口号*/
SOCKET sClient = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in sclient;
sclient.sin_family = AF_INET;
sclient.sin_port = htons(8888);
sclient.sin_addr.S_un.S_addr =inet_addr("192.168.0.105");
int nlen = sizeof(sclient);
/*输入想要发送的数据*/
cout << "please input data you want transport:" << endl;
string str;
getline(cin, str);
const int nLen = sizeof(str);
/*将string 类型的数据转换成char型数据并进行发送*/
char sendData[nLen];
strcpy_s(sendData, str.c_str());
/*利用sendto()函数进行数据发送,注意参数列表代表的含义。*/
sendto(sClient, (char*)sendData, strlen(sendData), 0, (sockaddr*)&sclient, nlen);
closesocket(sClient);
WSACleanup();
system("pause");
return 0;
}
Server端:
#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <string>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main() {
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsadata;
if (WSAStartup(sockVersion,&wsadata)!=0)
{
cout << "WinSock startup failed!";
return 0;
}
/*创建一个监听套接字,用来作为监听客户端的发送信息状态*/
SOCKET slisten = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
/*将该套接字绑定到一个sokcaddr_in的结构体。*/
if (bind(slisten,(SOCKADDR*)&sin,sizeof(sin))==SOCKET_ERROR)
{
cout << "bind socket error!" << endl;
system("pause");
return 0;
}
//指向存有源地址的相关信息的缓冲区
sockaddr_in remoteddr;
int nlen = sizeof(remoteddr);
/*进入循环监听状态,使客户端一直处于循环监听客户端,并且接受由客户端发送是数据。*/
while (true)
{
char recdata[255];
int ret = recvfrom(slisten, recdata, 255, 0,(SOCKADDR*)&remoteddr,&nlen);
if (ret>0)
{
recdata[ret] = 0x00;
printf("接受一个链接:%s\t\r", inet_ntoa(remoteddr.sin_addr));
printf(recdata);
}
}
/*关闭套接字和WSA库*/
closesocket(slisten);
WSACleanup();
system("pause");
return 0;
}