现在,WINSOCKs是新鲜的,而不是C++的超量,我也这样说。 我撰写了一个网络Server和网络校友班,主要来自MSDN辅导。 客户将分送服务器256个大小的果园,包括每个标准键盘的状态(0意味着钥匙没有受到压力,1个意味着正在受到压力)。
在操作守则时,我首先开始服务器,然后开始客户。 他们相互交错。 然后,要求客户发出关键板缓冲。 缓冲器被送去,但服务器在以下几处hang:
receiveResult = recv(theClient, buffer, sizeof(buffer), 0);
每一类别中的“钥匙”变量是每个关键国家的char钥匙[256]。
下面是网络Server一旦启动就会出现的 lo:
char buffer[256];
int receiveResult, sendResult;
// Receive from the client
do
{
receiveResult = recv(theClient, buffer, sizeof(buffer), 0);
if (receiveResult > 0 )
{
sendResult = send(theClient, buffer, receiveResult, 0);
if (sendResult == SOCKET_ERROR)
{
sendResult = WSAGetLastError();
JBS::reportSocketError(nret, "server send()");
closesocket(theClient);
WSACleanup();
return;
}
else
{
memcpy(keys, buffer, sizeof(keys));
}
}
else if (receiveResult == 0)
cout << "Server closing." << endl;
else
{
receiveResult = WSAGetLastError();
JBS::reportSocketError(nret, "server receive()");
closesocket(theClient);
WSACleanup();
return;
}
} while (receiveResult > 0);
这里是网络发送方法:
char buffer[256];
memcpy(buffer, keys, sizeof(buffer));
nret = send(theSocket, buffer, sizeof(buffer),0);
if (nret == SOCKET_ERROR)
{
nret = WSAGetLastError();
JBS::reportSocketError(nret, "client send()");
closesocket(theSocket);
WSACleanup();
}
do
{
char buff[256];
nret = recv(theSocket, buff, sizeof(buff), 0);
if (nret > 0)
{
memcpy(keys, buff, sizeof(keys));
}
else if (nret == 0)
cout << "Server connection closed" << endl;
else
{
nret = WSAGetLastError();
JBS::reportSocketError(nret, "client receive()");
closesocket(theSocket);
WSACleanup();
}
} while (nret > 0);
正如我所说的那样,在客户和服务器之间建立了联系,但接收部分的流程似乎没有发挥作用。 希望得到任何帮助。
网络启动方法:
sockVersion = MAKEWORD(1, 1);
// Initialize Winsock as before
WSAStartup(sockVersion, &wsaData);
// Store information about the server
LPHOSTENT hostEntry;
hostEntry = gethostbyname(serverAddress); // Specifying the server by its name;
if (!hostEntry) {
nret = WSAGetLastError();
JBS::reportSocketError(nret, "client gethostbyname()"); // Report the error as before
closesocket(theSocket);
WSACleanup();
}
// Create the socket
theSocket = socket(AF_INET, // Go over TCP/IP
SOCK_STREAM, // This is a stream-oriented socket
IPPROTO_TCP); // Use TCP rather than UDP
if (theSocket == INVALID_SOCKET) {
nret = WSAGetLastError();
JBS::reportSocketError(nret, "client socket()");
closesocket(theSocket);
WSACleanup();
}
// Fill a SOCKADDR_IN struct with address information
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
serverInfo.sin_port = htons(PORT); // Change to network-byte order and
// insert into port field
// Connect to the server
nret = connect(theSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
if (nret == SOCKET_ERROR)
{
nret = WSAGetLastError();
JBS::reportSocketError(nret, "client connect()");
closesocket(theSocket);
WSACleanup();
}
// Successfully connected!
started = true;