我正在开发一个高级客户端 - 服务器程序,我将一个游戏手柄的代码(已按下的按钮)发送到服务器。由于我发送了多个游戏手柄代码,在我的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;
}
正如您所注意到的,客户端代码段不包含send函数。这是因为,正如我所说的,我并不总是发送相同的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而失败。为什么会这样?任何帮助将不胜感激。
答案 0 :(得分:0)
很难从您的代码中看出,但似乎int client()
应该是您的服务器的某种连接启动功能,然后您拨打send
,但您的SOCKET ConnectSocket;
是本地到client()
...你还有套接字句柄的全局声明吗?也许您打算从ConnectSocket
返回client()
?此外,我强烈建议不要按每按一次按键。我建议使用单个持久连接,即连接一次,然后在必要时发送。