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