I 'm working on an advanced client-server program, where I send the codes of a joypad (buttons that have been pressed) to a server. Since I send more than one joypad codes, in one passage of my C++ code, I have to repeat the client code segment.
I thought of calling a function each time I have something to send.
client funcion:
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;
}
As you have noticed, the client code segment, doesn't include the send function. This is because, as I said, I don't send always the same char variable. Depending on the button that have been pressed, there is a different char to send. For example:
code segment (sending Δ and O buttons):
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);}
}
However, send function fails with SOCKET_ERROR. Why does that happen? Any help would be appreciated.
Hard to tell from your code but it seems like int client()
is supposed to be some kind of connection-initiation function to your server and then you call send
, but your SOCKET ConnectSocket;
is local to client()
... do you also have a global declaration of the socket handle? Perhaps you meant to return ConnectSocket
from client()
? Also, I'd strongly recommend against a connect per-button-press. I'd recommend a single, persistent connection, that is, connect once, and do send as necessary after that.