网络编程之udp

时间:2022-12-18 00:09:55
客户端:
#include<iostream>
#include<windows.h>
using namespace std;

#pragma comment(lib,"ws2_32.lib")
#define PORT 1688
#define IP "127.0.0.1"

int main()
{
INT Ret;
WSADATA wsaData;

if ((Ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
{
printf("WSAStartup() failes with error %d\n", Ret);
WSACleanup();
return -1;
}

SOCKET sockCli;
sockCli = socket(AF_INET, SOCK_DGRAM, 0);

SOCKADDR_IN addrSer;
addrSer.sin_addr.S_un.S_addr = inet_addr(IP);
addrSer.sin_family = AF_INET;
addrSer.sin_port = htons(PORT);

//与TCP相比较而言,省去了连接的步骤
  char send[256];
char recv[256];
int len = sizeof(SOCKADDR_IN);

while (1)
{
cout << "Cli:>";
cin >> send;
sendto(sockCli, send, strlen(send) + 1, 0, (SOCKADDR *)&addrSer, len);
cout << "Ser:>";
recvfrom(sockCli, recv, sizeof(recv), 0, (SOCKADDR *)&addrSer, &len);
cout << send << endl;
}

closesocket(sockCli);
WSACleanup();

return 0;
}


服务器端:

#include<iostream>

#include<windows.h>
using namespace std;

#pragma comment(lib,"ws2_32.lib")

#define PORT 1688
#define IP "127.0.0.1"

int main()
{
//协商版本号
INT Ret;
WSADATA wsaData;

if ((Ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
{
printf("WSAStartup() failes with error %d\n", Ret);
WSACleanup();
return -1;
}
//创建套接字
SOCKET sockSer;
sockSer = socket(AF_INET, SOCK_DGRAM, 0);

//创建地址结构体
SOCKADDR_IN addrSer, addrCli;
addrSer.sin_family = AF_INET;
addrSer.sin_port = htons(PORT);
addrSer.sin_addr.S_un.S_addr = inet_addr(IP);

//将地址与套接字绑定
int len = sizeof(SOCKADDR);
bind(sockSer, (SOCKADDR *)&addrSer, len);

cout << "server is waiting to link ...." << endl;
//进行连接
//accept(sockSer, (SOCKADDR *)&addrCli, &len);

char recv[256];
char send[256];

//少了等待连接的步骤
while (1)
{
recvfrom(sockSer, recv, sizeof(recv), 0, (SOCKADDR *)&addrCli, &len);
cout << "Cli:>" << recv << endl;
cin >> send;
sendto(sockSer, send, strlen(send) + 1, 0, (SOCKADDR *)&addrCli, len);
}

closesocket(sockSer);
WSACleanup();

return 0;
}