📄 winsockcomm1.cpp
字号:
else
{
return 0;
}
return 1;
}
//======================================================================================
void
Print(
TCHAR *pFormat,
...)
{
va_list ArgList;
TCHAR Buffer[256];
va_start (ArgList, pFormat);
(void)wvsprintf (Buffer, pFormat, ArgList);
SendDlgItemMessage (gDemoDlg, ID_RCVTEXT, EM_REPLACESEL, 0, (LPARAM)Buffer);
/*
#ifndef UNDER_CE
_putts(Buffer);
#else
OutputDebugString(Buffer);
#endif
*/
va_end(ArgList);
}
DWORD WINAPI ServerThread (PVOID pArg)
{
SOCKET sock, SockServ;
int nFamily = DEFAULT_FAMILY;
int nSockType = DEFAULT_SOCKTYPE;
char *szPort = DEFAULT_PORT;
SOCKADDR_STORAGE ssRemoteAddr;
int i, nNumSocks, cbRemoteAddrSize, cbXfer, cbTotalRecvd;
WSADATA wsaData;
ADDRINFO Hints, *AddrInfo = NULL, *AI;
fd_set fdSockSet;
char pBuf[BUFFER_SIZE];
char szRemoteAddrString[128];
HWND hDlg;
hDlg = (HWND)pArg;
if(WSAStartup(MAKEWORD(2,2), &wsaData))
{
// WSAStartup failed
return 1;
}
sock = INVALID_SOCKET;
//
// Get a list of available addresses to serve on
//
memset(&Hints, 0, sizeof(Hints));
Hints.ai_family = nFamily;
Hints.ai_socktype = nSockType;
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
if(getaddrinfo(NULL, szPort, &Hints, &AddrInfo))
{
Print(TEXT("ERROR: getaddrinfo failed with error %d\r\n"), WSAGetLastError());
goto Cleanup;
}
//
// Create a list of serving sockets, one for each address
//
AI = AddrInfo;
// SockServ = socket(nFamily, nSockType, 0);
SockServ = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
if (SockServ != INVALID_SOCKET)
{
if (bind(SockServ, AI->ai_addr, AI->ai_addrlen) == SOCKET_ERROR)
closesocket(SockServ);
else
{
if(nSockType == SOCK_STREAM)
{
if (listen(SockServ, 5) == SOCKET_ERROR)
{
closesocket(SockServ);
}
}
Print(
TEXT("Socket 0x%08x ready for connection with %hs family, %hs type, on port %hs\r\n"),
SockServ,
(AI->ai_family == AF_INET) ? "AF_INET" : ((AI->ai_family == AF_INET6) ? "AF_INET6" : "UNKNOWN"),
(AI->ai_socktype == SOCK_STREAM) ? "TCP" : ((AI->ai_socktype == SOCK_DGRAM) ? "UDP" : "UNKNOWN"),
szPort);
}
}
freeaddrinfo(AddrInfo);
//
// Wait for incomming data/connections
//
cbRemoteAddrSize = sizeof(ssRemoteAddr);
while (1)
{
sock = accept(SockServ, (SOCKADDR*)&ssRemoteAddr, &cbRemoteAddrSize);
if(sock == INVALID_SOCKET)
{
Print(TEXT("ERROR: accept() failed with error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
Print(TEXT("Accepted TCP connection from socket 0x%08x\r\n"), sock);
//
// Receive data from a client
//
cbTotalRecvd = 0;
do
{
cbRemoteAddrSize = sizeof(ssRemoteAddr);
cbXfer = recvfrom(sock, pBuf + cbTotalRecvd, sizeof(pBuf) - cbTotalRecvd, 0,
(SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
cbTotalRecvd += cbXfer;
} while(cbXfer > 0 && cbTotalRecvd < sizeof(pBuf));
if(cbXfer == SOCKET_ERROR)
{
Print(TEXT("ERROR: Couldn't receive the data! Error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
else if(cbXfer == 0)
{
Print(TEXT("ERROR: Didn't get all the expected data from the client!\r\n"));
goto Cleanup;
}
if(nSockType == SOCK_STREAM)
{
cbRemoteAddrSize = sizeof(ssRemoteAddr);
getpeername(sock, (SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
}
if (getnameinfo((SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize,
szRemoteAddrString, sizeof(szRemoteAddrString), NULL, 0, NI_NUMERICHOST) != 0)
strcpy(szRemoteAddrString, "");
Print(TEXT("SUCCESS - Received %d bytes from client %hs\r\n"), cbTotalRecvd, szRemoteAddrString);
//
// Echo the data back to the client
//
cbXfer = 0;
cbXfer = sendto(sock, pBuf, cbTotalRecvd, 0, (SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize);
if(cbXfer != cbTotalRecvd)
Print(TEXT("ERROR: Couldn't send the data! error = %d\r\n"), WSAGetLastError());
else
Print(TEXT("SUCCESS - Echo'd %d bytes back to the client\r\n"), cbXfer);
}
Cleanup:
for(i = 0; i < nNumSocks && SockServ != INVALID_SOCKET; i++)
closesocket(SockServ);
if(sock != INVALID_SOCKET)
{
shutdown(sock, SD_BOTH);
closesocket(sock);
}
WSACleanup();
return 0;
}
//============================================================================================
int _tmainClient(void)
{
SOCKET sock = INVALID_SOCKET;
int nFamily = DEFAULT_FAMILY;
int nSockType = DEFAULT_SOCKTYPE;
// char szRemoteName[64];
char szRemoteName[]="192.168.100.48";
char *szPort = DEFAULT_PORT;
SOCKADDR_STORAGE ssRemoteAddr;
int cbXfer, cbTotalRecvd, cbRemoteAddrSize;
WSADATA wsaData;
ADDRINFO Hints, *AddrInfo = NULL, *AI;
char szRemoteAddrString[128];
fd_set fdReadSet;
TIMEVAL timeout = {TIMEOUT_SECS, TIMEOUT_USECS};
char pRecvBuf[BUFFER_SIZE];
/*
if(argc < 2)
{
Print(TEXT("Server name/address parameter required. Ex: clnt 123.45.67.89"));
goto Cleanup;
}
else
{
// we use the first argument as the server name/address
#if defined UNICODE
wcstombs(szRemoteName, argv[1], sizeof(szRemoteName));
#else
strncpy(szRemoteName, argv[1], sizeof(szRemoteName));
#endif
Print(TEXT("Communicating with server - %hs\r\n"), szRemoteName);
}
*/
//
// Resolve the server name/address
//
//MessageBox(NULL, TEXT("Start Client"), TEXT(""), MB_OK);
memset(&Hints, 0, sizeof(Hints));
Hints.ai_family = nFamily;
Hints.ai_socktype = nSockType;
if(getaddrinfo(szRemoteName, szPort, &Hints, &AddrInfo))
{
Print(TEXT("ERROR: Couldn't get resolve the server name/address!"));
goto Cleanup;
}
//
// Attempt to connect to each address until we find one that succeeds
//
AI = AddrInfo;
sock = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
if (sock != INVALID_SOCKET)
{
if (AI->ai_socktype == SOCK_STREAM)
{
if(connect(sock, AI->ai_addr, AI->ai_addrlen) == SOCKET_ERROR)
{
// Connect failed, let's close this socket and try again on the next address in the list
closesocket(sock);
// MessageBox(NULL, TEXT("connect succeed"), TEXT(""), MB_OK);
}
}
// connect() succeeded or we're a UDP socket
}
else
MessageBox(NULL, TEXT("connect failed"), TEXT(""), MB_OK);
//
// Send data to the server
//
//MessageBox(NULL, TEXT("Start to sendto"), TEXT(""), MB_OK);
cbXfer = 0;
cbXfer = sendto(sock, pBuf, sizeof(pBuf), 0, AI->ai_addr, AI->ai_addrlen);
if(cbXfer != sizeof(pBuf))
{
Print(TEXT("ERROR: Couldn't send the data! error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
if (getnameinfo(AI->ai_addr, AI->ai_addrlen,
szRemoteAddrString, sizeof(szRemoteAddrString), NULL, 0, NI_NUMERICHOST) != 0)
strcpy(szRemoteAddrString, "");
Print(TEXT("SUCCESS - Sent %d bytes to address %hs\r\n"), cbXfer, szRemoteAddrString);
//
// Receive the echo'd data back from the server
//
// Vincent said : these can not be omitted, and why it failed
/*
FD_ZERO(&fdReadSet);
FD_SET(sock, &fdReadSet);
if(select(0, &fdReadSet, NULL, NULL, &timeout) != 1)
{
Print(TEXT("ERROR: Server hasn't responded in %d milliseconds\r\n"),
((timeout.tv_sec * 1000) + (timeout.tv_sec / 1000)));
goto Cleanup;
}
*/
cbTotalRecvd = 0;
do
{
cbRemoteAddrSize = sizeof(ssRemoteAddr);
// If we added below two MessageBox calls and omit select() call, nothing error, if marked them, it failed.
// It seems to fast to call recvfrom(), we should add code to check if sock is available
//MessageBox(NULL, TEXT("client call recvfrom"), TEXT(""), MB_OK);
cbXfer = recvfrom(sock, pRecvBuf + cbTotalRecvd, sizeof(pRecvBuf) - cbTotalRecvd, 0,
(SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
//MessageBox(NULL, TEXT("client received"), TEXT(""), MB_OK);
cbTotalRecvd += cbXfer;
} while(cbXfer > 0 && cbTotalRecvd < sizeof(pRecvBuf));
if(cbXfer == SOCKET_ERROR)
{
Print(TEXT("ERROR: Couldn't receive the data! Error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
else if(cbTotalRecvd != sizeof(pRecvBuf))
{
Print(TEXT("ERROR: Server didn't send back all the expected data!\r\n"));
goto Cleanup;
}
if(nSockType == SOCK_STREAM)
{
memset(&ssRemoteAddr, 0, sizeof(ssRemoteAddr));
cbRemoteAddrSize = sizeof(ssRemoteAddr);
getpeername(sock, (SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
}
if (getnameinfo((SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize,
szRemoteAddrString, sizeof(szRemoteAddrString), NULL, 0, NI_NUMERICHOST) != 0)
strcpy(szRemoteAddrString, "");
Print(TEXT("SUCCESS - Received %d bytes back from address %hs\r\n"), cbTotalRecvd, szRemoteAddrString);
Cleanup:
if(sock != INVALID_SOCKET)
{
shutdown(sock, SD_BOTH);
closesocket(sock);
}
if(AddrInfo)
freeaddrinfo(AddrInfo);
// WSACleanup();
return 0;
}
//=========================================================================
char * ConvertUnicodeToAscii(LPCWSTR p,int l)
{
char *Out;
int nChars;
nChars=WideCharToMultiByte(CP_ACP,
0,p,l,NULL,0,NULL,NULL);
if(nChars!=0)
{
Out=(char *)malloc(nChars+1);
if(Out!=NULL)
{
memset(Out,0,nChars+1);
nChars=WideCharToMultiByte(CP_ACP,
0,p,l,Out,nChars,NULL,NULL);
if(nChars==0)
{
free(Out);
Out=NULL;
}
}
}
else
Out=NULL;
if(Out==NULL)
{
Out=(char *)malloc(sizeof(char));
*Out=0;
}
return Out;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -