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

1、客户端:


#include "json//json.h"
#include 

#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 
#include 
#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传输_第1张图片

你可能感兴趣的:(Windows,C/C++)