I've been creating a socket programming code.
and I implemented server-side program as follow:
#include "Common.h"
#include "EP_Test4.h"
int main()
{
printf("Start EP3 \n");
while (1){
EP_Test4 et;
}
return 0;
}
this is a main code. and as you can see a code line is in while-statement. in there, a class is called, the constructor in the class is also called, then the "initEntryPoint()"method is called .
EP_Test4::EP_Test4(){
initEntryPoint();
}
in the initEntryPoint code, there are an initiation of socket method (InitCtrlSocket), a receiving data method and closing socket method.
void EP_Test4::initEntryPoint()
{
printf("[Waiting Restart Signal] \n");
CSocket cCtrlEpSock;
cCtrlEpSock.InitCtrlSocket();
cCtrlEpSock.RecvRestartEPMsg();
cCtrlEpSock.CloseCtrlSocket();
}
And those method are implemented like as follows
void CSocket::InitCtrlSocket(){
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("error\r\n");
}
if ((EpCtrlServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))<0)
{
perror("socket error : ");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(6870);
if (bind(EpCtrlServerSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
perror("bind error: ");
exit(1);
}
if (listen(EpCtrlServerSocket, 5)<0)
{
perror("listen error : ");
exit(1);
}
EpCtrlClientSocket = accept(EpCtrlServerSocket, (struct sockaddr *)&client_addr, &clen);
}
void CSocket::RecvRestartEPMsg(){
char arrRecvCompleteMsg[50];
memset(&arrRecvCompleteMsg, 0, sizeof(arrRecvCompleteMsg));
int data_len = recv(EpCtrlClientSocket, (char*)&arrRecvCompleteMsg, sizeof(arrRecvCompleteMsg), 0);
cout << "RECV CTRL MSG : " << arrRecvCompleteMsg << endl;
}
void CSocket::CloseCtrlSocket(){
closesocket(EpCtrlServerSocket);
closesocket(EpCtrlClientSocket);
WSACleanup();
}
But when the program is executed, the accept method and the recv method are not waiting. so printed messages are repeated like below image.
sometimes works well(waiting at the blocking method), sometimes not. I don't understand why this happen. As I know, accept method and recv method are the "blocking" method. But why those methods do sometimes block, sometimes not?