TCPIP网络编程(尹圣雨)UDP 轮流收发消息(windows)
端口号写的是 2345
客户端
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using std::cout;
using std::endl;
using std::cin;
int main()
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "startup error" << endl;
}
sockaddr_in sd;
sd.sin_port = htons(2345);
sd.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sd.sin_family = AF_INET;
SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);
// connect(sock, (sockaddr *)&sd, sizeof(sd));
for (int i = 0; i < 10; ++i)
{
char buf[1024];
cout << "请输入文本:" << endl;
cin >> buf;
int len = sizeof(sd);
sendto(sock, buf, strlen(buf), 0, (sockaddr *)&sd, sizeof(sd));
len = sizeof(sd);
memset(&buf, 0, 1024);
recvfrom(sock, buf, 1024, 0,(sockaddr *)&sd, &len);
cout << "收到的数据:" << buf<<endl;
}
getchar();
closesocket(sock);
WSACleanup();
return 0;
}
服务端
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
using std::cout;
using std::endl;
using std::cin;
int main()
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "WSA Error" << endl;
return 0;
}
sockaddr_in sd;
sd.sin_family = AF_INET;
sd.sin_port = htons(2345);
sd.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
SOCKET sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET)
{
cout << "socket error" << endl;
return 0;
}
if (bind(sock, (sockaddr *)&sd, sizeof(sd)) == SOCKET_ERROR)
{
cout << "bind error" << endl;
return 0;
}
sockaddr_in clientSd;
for (int i = 0; i < 10; ++i)
{
char buf[1024] = "";
int len = sizeof(clientSd);
recvfrom(sock, buf, 1024, 0, (sockaddr *)&clientSd, &len);
cout << buf<<endl;
memset(&buf, 0, 1024);
cout << "请输入数据:" << endl;
cin >> buf;
sendto(
sock, buf, strlen(buf), 0, (sockaddr *)(&clientSd),
sizeof(clientSd));
}
closesocket(sock);
WSACleanup();
return 0;
}