SOCKET
http://www.a766.com/plc/112387.htmlhttp://www.a766.com/plc/112387.html
????????
BOOL CMFCApplicationSocketClientDemoDlg::ConnectServerSocket(CMFCApplicationSocketClientDemoDlg* pClient)
{
CSoceketInitConfig ClientSockInit(2,2);
m_pClientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_pClientSock==NULL)
{
MessageBox(_T("ClientSocket创建失败!"),_T("信息提示:"),MB_OKCANCEL|MB_ICONERROR);
return FALSE;
}
sockaddr_in ServerAddr_in;
ServerAddr_in.sin_family = AF_INET;
int m_SerPort = GetDlgItemInt(IDC_EDITSERVERPORT);
CString StrSerIp;
GetDlgItemText(IDC_IPADDRESS_SERVER,StrSerIp);
if (StrSerIp==_T("0.0.0.0")||m_SerPort > 65535 || m_SerPort < 1024|| m_SerPort==0)
{
MessageBox(_T("请输入正确端口(1024-65535)或IP地址,重新连接!"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
SetRevTextMsg(_T("请输入正确端口IP地址,重新连接"));
return FALSE;
}
char* pStrIP = CstringToWideCharArry(StrSerIp);
ServerAddr_in.sin_port = htons(m_SerPort);
ServerAddr_in.sin_addr.S_un.S_addr = inet_addr(pStrIP);
if (SOCKET_ERROR==connect(m_pClientSock, (sockaddr*)&ServerAddr_in, sizeof(ServerAddr_in)))
{
MessageBox(_T("服务器连接失败,请检查你填写的IP和端口是否错误!"), _T("信息提示:"), MB_OK | MB_ICONWARNING);
SetRevTextMsg(_T("服务器连接失败,请检查你填写的IP和端口是否错误!"));
return FALSE;
}
pClient->SetRevTextMsg(_T("连接服务器成功"));
pClient->m_CutDownConnect.EnableWindow( TRUE);
pClient->m_ConnectServer.EnableWindow(FALSE);
m_ServerConnectSucced = TRUE;
CString RevMsg;
while (true)
{
if (socket_Select(m_pClientSock,100,TRUE))
{
char recvBuff[MaxBufSize] = { 0 };
int iRead = recv(m_pClientSock, recvBuff, sizeof(recvBuff), 0);
if (iRead > 0)
{
RevMsg = CharArryToCstring(recvBuff);
pClient->SetRevTextMsg(StrSerIp + _T(">>") + RevMsg);
for (int i = 0; i < iRead; i++)
{
printf("recvBuff[%d]=%d\n",i, int(recvBuff[i]));
}
}
else
{
pClient->SetRevTextMsg(_T("已断线,请重新连接"));
pClient->m_CutDownConnect.EnableWindow(FALSE);
pClient->m_ConnectServer.EnableWindow(TRUE);
m_ServerConnectSucced = FALSE;
return TRUE;
}
}
}
return TRUE;
}
????????通信线程
DWORD WINAPI ConnectServerThread(LPCVOID lParam)
{
CMFCApplicationSocketClientDemoDlg* pClient = (CMFCApplicationSocketClientDemoDlg*)lParam;
if (pClient->ConnectServerSocket(pClient))
{
}
return 0;
}