|
服务端:
WORD wVersion = MAKEWORD(2,2);
WSADATA wsaData;
int err = WSAStartup(wVersion,&wsaData);
if(err != 0)
return 0;
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in SockAddr;
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
SockAddr.sin_port = htons(5001);
int nSockErr;
if(bind(ListenSocket, (struct sockaddr *)&SockAddr, sizeof(SockAddr)) == SOCKET_ERROR)
nSockErr = WSAGetLastError();
if(listen(ListenSocket, 5) == SOCKET_ERROR)
nSockErr = WSAGetLastError();
while(bIsNetworkRunning)
{
SOCKET connectSocket = accept(ListenSocket, NULL, NULL);
if(connectSocket == INVALID_SOCKET)
nSockErr = WSAGetLastError();
else
{
char pBuf[MAX_MSG_LEN];
memset(pBuf, 0, sizeof(char)*MAX_MSG_LEN);
//每次能走到这里,但是接收不到具体数据。n为-1
int n = recv(connectSocket, pBuf, MAX_MSG_LEN*sizeof(char), MSG_PEEK);
if(n>0)
{
//其他操作
}//end if(n>0)
else
nSockErr = WSAGetLastError();
}
closesocket(connectSocket);
}
closesocket(ListenSocket);
WSACleanup();
服务端:
wVersion = MAKEWORD(2,2);
err = WSAStartup(wVersion,&wsaData);
if(err != 0)
return ;
SOCKET connectSocket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servAddr.sin_port = htons(5001);
char pBuf[64] = "测试消息发送......";
if(connect(connectSocket, (struct sockaddr *)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
printf("连接错误\n");
else
{
//这里发送是正确的,发送完n为字符串长度
int n = send(connectSocket, pBuf, strlen(pBuf), MSG_DONTROUTE);
if(n<0)
int nSockErr = WSAGetLastError();
}
closesocket(connectSocket);
WSACleanup(); |
|