求教大佬recv一直为-1的问题
新手写TCP协议时recv的返回值一直为-1,能发送,正常连接,求各位大佬解答,代码如下
UINT CMFCApplication3Dlg::recv_thd(LPVOID p)
{
int res;
char *msg;
CMFCApplication3Dlg * dlg = (CMFCApplication3Dlg*)AfxGetApp()->GetMainWnd();
CMFCApplication3Dlg m_dlg;
while (1)
{
//AfxMessageBox(_T("接收线程开启"));
res = recv(m_dlg.sock, msg, sizeof(msg), 0);
if (res == -1 || m_dlg.CloseConnect)//中断连接,数据接收失败或手动中断先调用发送函数给服务器放一段字符后关闭连接
{
AfxMessageBox(_T("Close"));
break;
}
else
{
msg[res] = '\0';
dlg->Update(_T("server:") + CString(msg));
//m_dlg.SetDlgItemText(IDC_LIST1, _T("server:")+ CString(msg));
CString str;
m_dlg.GetDlgItemText(IDC_LIST1, str);
if (str == L"server:This is Picture")
{
if (!m_dlg.Picture())
m_dlg.OnBnClickedButton2();
}
}
}
closesocket(m_dlg.sock);
return 0;
}
void CMFCApplication3Dlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
CloseConnect = 1;
OnBnClickedButton1();
MessageBox(_T("连接中断"));
}
void CMFCApplication3Dlg::OnBnClickedButton4()
{
// TODO: 在此添加控件通知处理程序代码
WSADATA wasData;
WORD wVersion;
wVersion = MAKEWORD(2, 2);
WSAStartup(wVersion, &wasData);
BYTE nArrIP[4];
m_IP = (CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1);
m_IP->GetAddress(nArrIP[0], nArrIP[1], nArrIP[2], nArrIP[3]);
u_short str;
str = GetDlgItemInt(IDC_EDIT1);
CString STemp;
STemp.Format(_T("%d"), str);
MessageBox(STemp);
CString buf;
buf.Format(_T("%d.%d.%d.%d"),nArrIP[0], nArrIP[1], nArrIP[2], nArrIP[3]);
MessageBox(buf);
if (!sock.Create(0, SOCK_STREAM, buf))
{
AfxMessageBox(_T("Error!"));
return;
}
if ( ! sock.Connect(buf, str))
{
AfxMessageBox(_T("FALSE"));
return;
}
else
{
AfxMessageBox(_T("连接成功"));
CloseConnect = 0;
AfxBeginThread(&recv_thd,0,0,0,NULL);
}
}
//发送
void CMFCApplication3Dlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CString str;
char *buf;
//str = GetDlgItemInt(IDC_EDIT2);
if(CloseConnect == 0)
GetDlgItemText(IDC_EDIT2,str);
else
str =_T("Close the Connect");
USES_CONVERSION; //cstring 转char*
buf = T2A(str);
if (send(sock, buf, strlen(buf), 0) == SOCKET_ERROR)
AfxMessageBox(_T("FALSE"));
else if (str == " ")
AfxMessageBox(_T("输入不能为空"));
else
{
Update(_T("client:") + str);
m_SendEdit->SetWindowText(_T(" "));
m_SendEdit->SetFocus();
}
}