我正在开发一个高级客户端-服务器程序,我将游戏手柄的代码(已按下的按钮)发送到服务器。由于我发送了多个手柄代码,因此在我的 C++ 代码的一段中,我必须重复客户端代码段。
每次我有东西要发送时,我都想调用一个函数。
客户端功能:
int client()
{
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
MessageBox(NULL, TEXT("Winsock initialization, done unsuccessfully"), TEXT("Diploma thesis"), MB_ICONERROR | MB_OK);
return 1;
}
// Create a socket for connecting to server.
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
MessageBox(NULL, TEXT("Socket creation for connecting to server, done unsuccessfully"), TEXT("Diploma thesis"), MB_ICONERROR | MB_OK);
WSACleanup();
return 1;
}
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sockaddr_in Service;
memset(&Service, 0, sizeof(Service));
Service.sin_family = AF_INET;
Service.sin_addr.s_addr = inet_addr("127.0.0.1");
Service.sin_port = htons(5004);
// Connect to server.
iResult = connect(ConnectSocket, (SOCKADDR *) &Service, sizeof (Service));
if (iResult == SOCKET_ERROR) {
iResult = closesocket(ConnectSocket);
MessageBox(NULL, TEXT("Connection with server, done unsuccessfully"), TEXT("Diploma thesis"), MB_ICONERROR | MB_OK);
WSACleanup();
return 1;
}
如您所见,客户端代码段不包含发送功能。这是因为,正如我所说,我并不总是发送相同的 char 变量。根据按下的按钮,发送不同的字符。例如:
代码段(发送 Δ 和 O 按钮):
client();
if (send(ConnectSocket, c_szText1, sizeof(c_szText1), 0) == SOCKET_ERROR)
{MessageBox(NULL, TEXT("The message could not be sent"), TEXT("Diploma thesis"), MB_ICONERROR | MB_OK);}
}
client();
if (send(ConnectSocket, c_szText2, sizeof(c_szText2), 0) == SOCKET_ERROR)
{MessageBox(NULL, TEXT("The message could not be sent"), TEXT("Diploma thesis"), MB_ICONERROR | MB_OK);}
}
但是,发送函数因 SOCKET_ERROR 而失败。为什么会这样?任何帮助,将不胜感激。