很久没有手写udp通讯了,而且以前也没有在windows下写过,今天写一下,熟悉一下
- 发送端代码:
#include <iostream>
#include <string>
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WSADATA WSAdata;
if (!WSAStartup(MAKEWORD(2, 2), &WSAdata))
{
cout << "初始化成功" << endl;
}
else
{
cout << "初始化失败!" << endl;
exit(1);
}
SOCKET send_sock = -1;
send_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (send_sock == INVALID_SOCKET)
{
cout << "socket fail" << endl;
exit(1);
}
cout << "sock: " << send_sock << endl;
//要发送到的地址信息
SOCKADDR_IN to;
to.sin_family = AF_INET;
to.sin_port = htons(8888);
to.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//可选项,udp建立连接后,理论上效率会更高
//connect(send_sock, (sockaddr *)&to, sizeof to);
while (1)
{
//发送数据
char buf[1024] = "";
cout << "请输入:";
cin >> buf;
int num = sendto(send_sock, buf, strlen(buf), 0, (sockaddr *)&to, sizeof to);
cout << "发送的字节数: " << num << endl;
}
closesocket(send_sock);
WSACleanup();
system("pause");
return 0;
}
- 接收端代码:
#include <iostream>
#include <string>
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WSADATA WSAdata;
if (!WSAStartup(MAKEWORD(2, 2), &WSAdata))
{
cout << "初始化成功" << endl;
}
else
{
cout << "初始化失败" << endl;
exit(1);
}
SOCKET server_sock = -1;
server_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (server_sock == INVALID_SOCKET) //这个值是-1
{
cout << "socket fail" << endl;
exit(1);
}
cout << "server socket: " << endl;
//绑定的地址
SOCKADDR_IN server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.S_un.S_addr = INADDR_ANY;
bind(server_sock, (sockaddr *)&server_addr, sizeof server_addr);
char buf[1024] = "";
while (1)
{
int num = -1;
memset(buf, 0, sizeof buf);
num = recv(server_sock, buf, sizeof buf, 0);
cout << "接收到的字节数: " << num << "字节" << endl;
cout << "接收到的数据: " << buf << endl;
}
closesocket(server_sock);
WSACleanup();
system("pause");
return 0;
}
- 运行结果
- 添加一个发送文件的代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WSADATA WSAdata;
if (!WSAStartup(MAKEWORD(2, 2), &WSAdata))
{
cout << "初始化成功" << endl;
}
else
{
cout << "初始化失败!" << endl;
exit(1);
}
SOCKET send_sock = -1;
send_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (send_sock == INVALID_SOCKET)
{
cout << "socket fail" << endl;
exit(1);
}
cout << "sock: " << send_sock << endl;
//要发送到的地址信息
SOCKADDR_IN to;
to.sin_family = AF_INET;
to.sin_port = htons(8888);
to.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//打开文件
FILE *fd = fopen("UDPTrans.cpp", "rb");
if (fd == NULL)
{
perror("fopen");
exit(1);
}
int num = -1;
getchar();
while (!feof(fd))
{
//发送数据
char buf[1024] = "";
num = fread(buf, sizeof buf - 1, 1, fd);
cout << buf << endl;
num = sendto(send_sock, buf, strlen(buf), 0, (sockaddr *)&to, sizeof to);
cout << buf << endl;
}
closesocket(send_sock);
WSACleanup();
system("pause");
return 0;
}