C++解析JSON进行网络传输--一个通过JSON方式的socket传输

1、客户端:


#include "json//json.h"
#include <WinSock2.h>

#pragma comment(lib, "WS2_32.lib")
#pragma comment(lib, "json_vc71_libmtd.lib")

int main()
{
	Json::Value val;
	Json::StyledWriter style_write;

	val["name"] = "xiaoli" ;

	WSADATA wsaData;
	SOCKET SendSocket;
	sockaddr_in RecvAddr;
	int Port = 27015;
	
	//初始化Socket
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	//创建Socket对象
	SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	//设置服务器地址
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(Port);
	RecvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

	std::string SendBuf = style_write.write(val);

	//向服务器发送数据
	sendto(SendSocket, SendBuf.c_str(), SendBuf.size(), 0, (SOCKADDR*)&RecvAddr, sizeof(RecvAddr));

	closesocket(SendSocket);
	WSACleanup();

	getchar();
	return 0;
}

2、服务器端:

#include <iostream>
#include <WinSock2.h>
#include "json/json.h"

#pragma comment(lib, "WS2_32.lib")
#pragma comment(lib, "json_vc71_libmtd.lib")
int main()
{
	//初始化socket
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);
	//创建socket
	SOCKET RecvSocket;
	RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	//设置服务器地址
	sockaddr_in RecvAddr;
	int Port = 27015;
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(Port);
	RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	//绑定socket
	bind(RecvSocket, (SOCKADDR*)&RecvAddr, sizeof(RecvAddr));

	char RecvBuf[1024];
	int BufLen = 1024;
	sockaddr_in SenderAddr;
	int SendAddrSize = sizeof(SenderAddr);

	recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR*)&SenderAddr, &SendAddrSize);

	std::string strName;
	Json::Value val;
	Json::Reader reader;
	if (reader.parse(RecvBuf, val))
	{
		strName = val["name"].asString();
	}

	std::cout << strName << std::endl;

	closesocket(RecvSocket);
	WSACleanup();

	getchar();
	return 0;
}

3、成功结果:


C++解析JSON进行网络传输--一个通过JSON方式的socket传输,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。