|
-
December 22nd, 2009, 08:55 AM
#1
invalid socket in accept()
hello my friend....
i try to built socket aplication in thread . usually i did not get error in my aplication when i implemented accept() function. but in these code i got error.
Code:
void CComputer::OnButtonStart()
{
// TODO: Add your control notification handler code here
WSADATA wsd;
CString str, m_sError;
int iSize;
CString status;
CWaitCursor wait;
UpdateData(TRUE);
for (int i=0; i<40; i++ )
sClient[i] = NULL;
//cek port input
if(m_sPort.IsEmpty())
{
AfxMessageBox("Please Insert Port Number...!!");
m_cStartBtn.EnableWindow(TRUE);
return;
}
// cek winsock2
if (WSAStartup(MAKEWORD(2,2), &wsd) !=0)
{
AfxMessageBox("Failed to Load Winsock....!!");
return;
}
// inisialisasi soket dan port
sServer=socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (sServer ==SOCKET_ERROR)
{
m_sError.Format("socket() failed : %d ", WSAGetLastError());
AfxMessageBox(m_sError);
return;
}
//port
sadd_Server.sin_family = AF_INET;
sadd_Server.sin_port = htons(atoi(m_sPort));
sadd_Server.sin_addr.s_addr = htonl (INADDR_ANY);
iSize = sizeof(sadd_Server);
int opt,reuse;
reuse = setsockopt(sServer, SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof (opt));
if (reuse == SOCKET_ERROR)
{
//close(); // close.
m_sError.Format("failed reuse socket : %d ", WSAGetLastError());
return;
}
// bind : mengikat antara aplikasi dengan port yang dibuat
if(bind(sServer, (struct sockaddr *)&sadd_Server, iSize) == SOCKET_ERROR)
{
m_sError.Format("bind() failed : %d " , WSAGetLastError());
AfxMessageBox(m_sError);
return;
}
nClients=0;
// status.Format(" running");
m_sStatus.SetWindowText("running");
//refresh database
SetTimer(1,1000,NULL);
//listen port dengan backlog maksimum
listen(sServer,SOMAXCONN);
m_cStartBtn.EnableWindow(FALSE);
m_cStopBtn.EnableWindow(TRUE);
//looping, dengan menggunakan thread
AfxBeginThread(&thread,0);
}
UINT thread(LPVOID p)
{
int iSize;
int s=1,msgcount,loop=1,flag=0;
CString data, data_send;
CComputer *dlg=(CComputer*)AfxGetApp()->GetMainWnd();
msgcount=dlg->nClients;
iSize=sizeof(dlg->sadd_Client);
dlg->sClient[msgcount]=accept(dlg->sServer,(struct sockaddr *)&(dlg->sadd_Client),&iSize);
if (dlg->sClient[msgcount]==INVALID_SOCKET)
{
AfxMessageBox("Error : invalid socket");
dlg->m_cStartBtn.EnableWindow(TRUE);
return 0;
}else
{
AfxMessageBox(" socket is ready");
dlg->m_cStartBtn.EnableWindow(TRUE);
}
return 0;
}
when i run my aplication, i got messagebox "Error : invalid socket". from that messagebox we know that my accept() function got error.
any suggestin how to correct it?? what should i do??
thanks,,,
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|