TCP UDP HTTP

TCP

// socket通信
	SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == INVALID_SOCKET)
	{
		CCLOG("create socket error");
		return;
	}

	// 连接服务器
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = inet_addr("192.168.192.132");
	addr.sin_port = htons(23889); // 65535

	// 连接服务器
	connect(sock, (sockaddr*)&addr, sizeof(addr));

	// 发送数据给服务器
	send(sock, "Hello", 5, 0);
	send(sock, "Hello1", 6, 0); // HelloHello1

	char buf[1024];
	recv(sock, buf, sizeof(buf), 0);

	CCLOG("%s", buf);


UDP

// 创建UDP
	SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);

	// 连接服务器
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = inet_addr("192.168.192.132");
	addr.sin_port = htons(8989); // 65535

	sendto(sock, "HelloUDP", 9, 0, (sockaddr*)&addr, sizeof(addr));

HTTP

network::HttpClient* client = network::HttpClient::getInstance();

	network::HttpRequest* req = new network::HttpRequest();
	req->setUrl("http://192.168.192.132/cgi-bin/a.out?user=aaa&pass=bbbb");
	req->setResponseCallback(CC_CALLBACK_2(T25Network::httpResponse, this));
	req->setRequestType(network::HttpRequest::Type::POST);

	// POST额外数据
	Data data = FileUtils::getInstance()->getDataFromFile("d:\\blocks.png");
	req->setRequestData((const char*)data.getBytes(), data.getSize());

	/* GET表示向服务器索取数据
	   POST表示向服务器推送数据 */

	// 向服务器发送请求
	client->send(req);

	req->release();

httpResponse(network::HttpClient* , network::HttpResponse* response)
{
	CCLOG("code = %d\n", response->getResponseCode());
	//const char* data = response->getResponseDataString();
	std::vector<char>* data = response->getResponseData();

	std::string str;
	str.resize(data->size());

	std::copy(data->begin(), data->end(), str.begin());


	FILE* f = fopen("d:\\2.png", "wb");
	fwrite(str.c_str(), data->size(), 1, f);
	fclose(f);

#if 0
	std::string str;
	str.resize(data->size());
	
	std::copy(data->begin(), data->end(), str.begin());


	CCLOG("recv data: %s", str.c_str());
#endif



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值