求教大佬recv一直为-1的问题

Saltedefish 2020-09-04 09:58:35
新手写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();
}
}
...全文
672 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
孤独de猫 2020-09-06
  • 打赏
  • 举报
回复
socket 有阻塞式 和 非阻塞式,阻塞式的recv时,会一直卡住,直接接收到数据 或 socket 断开,非阻塞式,会一直返回-1,必须用WSAGETLAstErr 来获取错误代码来判断 socket的状态。 你也可以用开源的 HPSocket,蛮好用的。
zgl7903 2020-09-05
  • 打赏
  • 举报
回复
/*CMFCApplication3Dlg m_dlg;  不要*/
res = recv(/*m_dlg. */ dlg->sock, msg, sizeof(msg), 0);



an_bachelor 2020-09-04
  • 打赏
  • 举报
回复
最好的办法是看文档 Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. (也就是说:遇到SOCKET_ERROR 需要立即WSAGetLastError()来获知具体的错误信息): RETURN VALUE Error code Meaning WSANOTINITIALISED A successful WSAStartup call must occur before using this function. WSAENETDOWN The network subsystem has failed. WSAEFAULT The buf parameter is not completely contained in a valid part of the user address space. WSAENOTCONN The socket is not connected. WSAEINTR The (blocking) call was canceled through WSACancelBlockingCall. WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. WSAENETRESET For a connection-oriented socket, this error indicates that the connection has been broken due to keep-alive activity that detected a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired. WSAENOTSOCK The descriptor is not a socket. WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only send operations. WSAESHUTDOWN The socket has been shut down; it is not possible to receive on a socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH. WSAEWOULDBLOCK The socket is marked as nonblocking and the receive operation would block. WSAEMSGSIZE The message was too large to fit into the specified buffer and was truncated. WSAEINVAL The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative. WSAECONNABORTED The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable. WSAETIMEDOUT The connection has been dropped because of a network failure or because the peer system failed to respond. WSAECONNRESET The virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket as it is no longer usable. On a UDP-datagram socket, this error would indicate that a previous send operation resulted in an ICMP "Port Unreachable" message.
smwhotjay 2020-09-04
  • 打赏
  • 举报
回复
WSAGETLAstErr 获得错误代码。

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧