鉴于udp协议传输数据的方式,能够提供诸多便利,下面给出一个具体应用的简单示例:
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include "json.hpp"
#include <winsock2.h>
using json = nlohmann::json;
const int PORT = 8080;
const char* SERVER_IP = "127.0.0.1";
const int BUFFER_SIZE = 1024;
int main() {
// 初始化Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed\n";
return 1;
}
// 创建UDP套接字
SOCKET sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Error creating socket\n";
WSACleanup();
return 1;
}
// 设置服务器地址
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
// 绑定套接字到端口
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
std::cerr << "Bind failed\n";
closesocket(sockfd);
WSACleanup();
return 1;
}
while (true) {
char buffer[BUFFER_SIZE];
struct sockaddr_in client_addr;
int len = sizeof(client_addr);
// 接收数据
int recv_len = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr, &len);
if (recv_len == SOCKET_ERROR) {
std::cerr << "Error receiving data\n";
closesocket(sockfd);
WSACleanup();
return 1;
}
else
{
///* std::string s;
// s = buffer;*/
// nlohmann::json j = nlohmann::json::parse(s);
//
// 现在你可以访问 j 中的数据,例如:
// 将接收到的数据转换为nlohmann::json对象
buffer[recv_len] = '\0';
json received_json = json::parse(buffer);
std::string type = received_json["type"];
std::cout << type;
//解析数据,判断类型
if ("1" == type)
{
nlohmann::json hobbies;
hobbies["name"] = "John Doe";
hobbies["age"] = 30;
hobbies["is_student"] = false;
// 将 json 对象序列化为字符串
std::string json_string = hobbies.dump();
// 获取字符串的 char 数组表示
const char* char_array = json_string.c_str();
//发送这个类型的的json数据
sendto(sockfd, char_array, strlen(char_array), 0, (struct sockaddr*)&client_addr,len);
}
else if ("2" == type)
{
nlohmann::json hobbies;
hobbies["name"] = "John";
hobbies["age"] = 42;
hobbies["is_student"] = false;
// 将 json 对象序列化为字符串
std::string json_string = hobbies.dump();
// 获取字符串的 char 数组表示
const char* char_array = json_string.c_str();
//发送这个类型的的json数据
sendto(sockfd, char_array, strlen(char_array), 0, (struct sockaddr*)&client_addr, len);
}
}
}
// 关闭套接字和清理Winsock
closesocket(sockfd);
WSACleanup();
return 0;
}
编译程序后,可使用netassist软件来尽心发送和接收数据的测试。