0
下面的代碼創建一個服務器與客戶端進行通信。此代碼可以在HTTP上正常工作,但在HTTPS中無法正常工作。建議一個方法或網絡功能需要包含在ssl上正常工作。客戶端服務器Visual C++中的通信套接字編程
#define SOCKET_OK 0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nShow)
{
WORD sockVer;
WSADATA wsaData;
int retVal;
sockVer = MAKEWORD(2,2);
WSAStartup(sockVer, &wsaData);
/// Creating socket
SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(servSock == INVALID_SOCKET)
{
MessageBox(NULL, "Unable to create socket()", "SOCKET ERROR", MB_OK);
WSACleanup();
return SOCKET_ERROR;
}
/// Filling in sockaddr_in struct
SOCKADDR_IN sin;
sin.sin_family = PF_INET;
sin.sin_port = htons(1111);
sin.sin_addr.s_addr = INADDR_ANY;
retVal = bind(servSock, (LPSOCKADDR)&sin, sizeof(sin));
if(retVal == SOCKET_ERROR)
{
MessageBox(NULL, "Unable to bind", "SOCKET ERROR", MB_OK);
WSACleanup();
return SOCKET_ERROR;
}
/// Trying to listen socket
retVal = listen(servSock, 10);
if(retVal == SOCKET_ERROR)
{
MessageBox(NULL, "Unable to listen()", "SOCKET ERROR", MB_OK);
WSACleanup();
return SOCKET_ERROR;
}
/// Waiting for a client
SOCKET clientSock;
clientSock = accept(servSock, NULL, NULL);
if(clientSock == INVALID_SOCKET)
{
MessageBox(NULL, "Unable to accept()", "SOCKET ERROR", MB_OK);
WSACleanup();
return SOCKET_ERROR;
}
char szReq[8];
retVal = recv(clientSock, szReq, 8, 0);
if(retVal == SOCKET_ERROR)
{
MessageBox(NULL, "Unable to recv()", "SOCKET ERROR", MB_OK);
return SOCKET_ERROR;
}
MessageBox(NULL, szReq, "Got the request from client", MB_OK);
char *szResp = "Response";
MessageBox(NULL, szResp, "Sending response from server", MB_OK);
retVal = send(clientSock, szResp, strlen(szResp), 0);
if(retVal == SOCKET_ERROR)
{
MessageBox(NULL, "Unable to send()", "SOCKET ERROR", MB_OK);
return SOCKET_ERROR;
}
/// Closing socket
closesocket(clientSock);
closesocket(servSock);
WSACleanup();
return SOCKET_OK;
}