// client.cpp -- 客户端实现文件.
#include "stdafx.h"
#include <iostream>
#include <WinSock2.h>
#pragma comment (lib, "ws2_32.lib")
const int gc_MaxLengthOfQueue = 10 ;
const unsigned int guc_Port = 7100 ;
//发送的数据类型
struct data
{
unsigned int ID ;
unsigned int Type ;
};
int _tmain(int argc, _TCHAR* argv[])
{
//初始化要发送给服务端的数据.
struct data dataSendToServer = {11, 22};
//创建要从服务端接收的数据
struct data dataReceiveFromServer = {0, 0} ;
//合成套接字版本.
WORD wVersionRequested = MAKEWORD(2, 2) ;
WSADATA wsaData ;
//加载套接字库版本.
if (WSAStartup(wVersionRequested, &wsaData) != 0)
{
return 0 ;
}
if (LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup() ;
return 0 ;
}
//创建套接字.
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0) ;
//向服务器发出连接请求.
SOCKADDR_IN addrServer ;
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1") ;
addrServer.sin_family = AF_INET ;
addrServer.sin_port = htons(guc_Port) ;
connect(sockClient, reinterpret_cast<SOCKADDR *> (&addrServer), sizeof(addrServer)) ;
//接收服务器传来的数据.
recv(sockClient, reinterpret_cast<char *> (&dataReceiveFromServer), sizeof (dataReceiveFromServer), 0) ;
//打印从服务器传来的数据.
std ::cout << "ID: " << dataReceiveFromServer.ID << " Type: " << dataReceiveFromServer.Type << std ::endl ;
//向服务器发送数据.
send(sockClient, reinterpret_cast<char *> (&dataSendToServer), sizeof (dataSendToServer), 0) ;
//关闭套接字.
closesocket(sockClient) ;
WSACleanup() ;
std ::cin.get() ;
return 0;
}