void CTCPEchoClientDlg::OnButtonConnectServer()
{
// TODO: Add your control notification handler code here
//create socket and connect
CString tmp = _T("");
//create socket
g_hSocket = ::socket(PF_INET,SOCK_STREAM,0);
if( g_hSocket == INVALID_SOCKET){
tmp.Format(_T("Fail to create socket"),::WSAGetLastError());
AfxMessageBox(tmp);
return;
}
//create socket information (bind)
SOCKADDR_IN SockAddr;
::ZeroMemory(&SockAddr,sizeof(SockAddr));
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.S_un.S_addr = inet_addr(U_HOSTADDR);
SockAddr.sin_port = ::htons(U_CONNPORT);
//connect to server
if(::connect(g_hSocket,(SOCKADDR*)&SockAddr, sizeof(SOCKADDR_IN))!=0){
tmp.Format(_T("Fail to connect server. [Error Code: %d]"),::WSAGetLastError());
AfxMessageBox(tmp);
::closesocket(g_hSocket);
g_hSocket = NULL;
return;
}
AfxMessageBox(_T("Connect Server."));
SetDlgItemText(IDC_StaticStatus,_T("Connected"));
GetDlgItem(IDC_Button_ConnectServer)->EnableWindow(FALSE);
GetDlgItem(IDC_ButtonSend)->EnableWindow(TRUE);
GetDlgItem(IDC_ButtonDisconnect)->EnableWindow(TRUE);
}
void CTCPEchoClientDlg::OnButtonSend()
{
// TODO: Add your control notification handler code here
//send
if(g_hSocket == NULL){
AfxMessageBox(_T("Not Connected Server."));
return;
}
CString tmp = _T("");
char szBufferSend[U_BUFSIZE], szBufferRecv[U_BUFSIZE];
::ZeroMemory(szBufferSend,U_BUFSIZE);
::ZeroMemory(szBufferRecv,U_BUFSIZE);
sprintf(szBufferSend, _T("%s"), _T("Test String"));
int nLength = lstrlen(szBufferSend);
//sending string
if(nLength != ::send(g_hSocket,szBufferSend, nLength, 0)){
tmp.Format(_T("Fail to sending test string. [Error Code: %d]"),::WSAGetLastError());
AfxMessageBox(tmp);
return;
}
//print recieve test message from server
::recv(g_hSocket, szBufferRecv, U_BUFSIZE, 0);
AfxMessageBox(szBufferRecv);
}
void CTCPEchoClientDlg::OnButtonDisconnect()
{
// TODO: Add your control notification handler code here
// disconnect and close socket
if( g_hSocket == NULL){
AfxMessageBox(_T("not connected server."));
return;
}
GetDlgItem(IDC_Button_ConnectServer)->EnableWindow(TRUE);
GetDlgItem(IDC_ButtonSend)->EnableWindow(FALSE);
GetDlgItem(IDC_ButtonDisconnect)->EnableWindow(FALSE);
::shutdown(g_hSocket,SD_BOTH);
::closesocket(g_hSocket);
SetDlgItemText(IDC_StaticStatus,_T("Disconnected"));
AfxMessageBox(_T("Terminate connection on server."));
g_hSocket = NULL;
}
댓글