我把服务端代码下到嵌入式设备上,用PC的做客户端,没有问题。说明服务端接收和发送都没有问题,我把客户端的发送代码复制到服务端上,用PC测试也没问题,说明客户端发送代码没错。但是,客户端与PC连接后,PC始终收不到数据,我曾经判断发送状态也是“成功”。这是为什么呢?那位指点下谢谢!
服务端代码:
SOCKET m_UDPSocket; //UDP Socket通讯套接字
WSADATA wsa;
//加载winsock动态链接库
if (WSAStartup(MAKEWORD(1,1),&wsa) != 0)
{
return -1;//代表失败
}
SOCKADDR_IN localAddr;
SOCKADDR_IN fromAddr;
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(5050);
localAddr.sin_addr.s_addr=INADDR_ANY;
int fromlen =sizeof(fromAddr);
//创建UDP套接字
m_UDPSocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if (m_UDPSocket == INVALID_SOCKET)
{
return -1;
}
//绑定地址
if(bind(m_UDPSocket,(struct sockaddr*)&localAddr,sizeof(localAddr))!=0)
{
return -1;
}
while (1)
{
ZeroMemory(recvBuf,128);
if (recvfrom(m_UDPSocket,recvBuf,sizeof(recvBuf),0,(struct sockaddr*)&fromAddr,&fromlen)!=SOCKET_ERROR)
{
sendto(m_UDPSocket,(char*)&m_value,sizeof(m_value),0,(struct sockaddr*)&fromAddr,fromlen);
}
Sleep(100);
}
closesocket(m_UDPSocket);
WSACleanup();
客户端代码:
SOCKET m_ClientSocket; //UDP Socket通讯套接字
WSADATA wsa;
int iLen;
CString m_remoteHost,s;
char SendBuf[8];
SendBuf[0]= 0x68;
SendBuf[1]= 0x01;
SendBuf[2]= 0x00;
SendBuf[3]= 0x00;
SendBuf[4]= 0x19;
SendBuf[5]= (unsigned char)0x89;
SendBuf[6]= 0x11;
SendBuf[7]= 0x22;
SOCKADDR_IN localAddr;
//加载winsock动态链接库
if (WSAStartup(MAKEWORD(1,1),&wsa) != 0)
{
return -1;//代表失败
}
m_remoteHost = _T("192.169.1.201");
char ansiRemoteHost[255];
ZeroMemory(ansiRemoteHost,255);
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,m_remoteHost,wcslen(m_remoteHost),ansiRemoteHost,wcslen(m_remoteHost),NULL,NULL);
localAddr.sin_family=AF_INET;
localAddr.sin_port=htons(5050);
localAddr.sin_addr.s_addr=inet_addr(ansiRemoteHost);
// localAddr.sin_addr.s_addr=inet_addr("192.169.1.200");
iLen=sizeof(localAddr);
m_ClientSocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if (m_ClientSocket==INVALID_SOCKET)
{
AfxMessageBox(L"......09");
return -2;
}
connect(m_ClientSocket,(sockaddr*)&localAddr,sizeof(localAddr));
while(1)
{
sendto(m_ClientSocket,SendBuf,sizeof(SendBuf),0,(struct sockaddr*)&localAddr,iLen);
Sleep(10);
recvfrom(m_ClientSocket,(char*)&m_value,sizeof(m_value),0,(struct sockaddr*)&localAddr,&iLen);
Sleep(1000);
}
closesocket(m_ClientSocket);
WSACleanup();
------解决方案--------------------
这是个难题啊
------解决方案--------------------
客户端用得着绑定端口么?