各位大神好:
小弟做嵌入式开发,对windows下编程不太了解,有一个关于UDP通信的问题请教大家。
背景:PC给嵌入式设备发送UDP数据,嵌入式设备收到数据同样是用UDP包回复给PC。PC和嵌入式设备适用网线直接连接。
嵌入式设备ip:192.168.2.100,接收端口10002,在收到PC的UDP数据包后,向192.168.2.103,端口10003发送反馈的UDP数据包。
在网上拷贝了一些UDP通信示例代码,进行了修改。main函数负责发送UDP数据,起一个线程负责接收DUP数据。代码如下。现在的状况是,发送没有问题,嵌入式设备能够顺利收到数据,并且通过Wireshark可以看到嵌入式设备也回了UDP数据包,但是接收数据线程始终没有能够接收到数据......
奇怪的是,如果我将线程单独作为一个程序运行,而不是作为发送程序的一个线程,就能够顺利的收到嵌入式设备回复的UDP数据包。
#include<Winsock2.h>
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#pragma comment (lib,"ws2_32.lib")
int main(int argc,char *argv[])
{
SOCKET socketDSP;
SOCKADDR_IN DspSer;
unsigned int tmp = 0;
WSADATA wsaData;
SOCKET sClient;
int sendLen = 0;
WSAStartup(MAKEWORD(2,2),&wsaData);
DspSer.sin_family = AF_INET;
DspSer.sin_port = htons(DSP_PORT);
DspSer.sin_addr.s_addr = inet_addr("192.168.2.100");
socketDSP = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
HANDLE hThread=CreateThread(NULL,0,FunThread,0,0,0);//创建接收线程
CloseHandle(hThread);
while(1)
{
//Send UDP Pkg to DSP
}
return 0;
}
DWORD WINAPI FunThread(LPVOID)
{
unsigned int num = 0;
int iPort =10003;
WSADATA wsaData;
SOCKET sSocket;
int iLen;
int iSend;
int iRecv;
char recv_buf[4096] ;
struct sockaddr_in ser,cli;
if(WSAStartup(MAKEWORD(2,2),&wsaData) !=0 )
{
printf("Failed to load Winsock \n");
return 0;
}
sSocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sSocket == INVALID_SOCKET)
{
printf("socket() Failed :%d \n",WSAGetLastError());
return 0;
}
ser.sin_family = AF_INET;
ser.sin_port = htons(iPort);
ser.sin_addr.s_addr = inet_addr("192.168.2.103");
if(bind(sSocket,(LPSOCKADDR)&ser,sizeof(ser)) == SOCKET_ERROR)
{
printf("bind() failed: %d \n",WSAGetLastError());
return 0;
}
int iMode = 1;//0 == block, 1 == non-block
ioctlsocket(sSocket, FIONBIO, (u_long FAR*) &iMode);
iLen = sizeof(cli);
while(1)
{
memset(recv_buf,0,sizeof(recv_buf));
iRecv = recvfrom(sSocket,recv_buf,4096,0,(SOCKADDR *)&cli,&iLen);
if(iRecv == SOCKET_ERROR)
{
printf("recvfrom() Failed: %d \n",WSAGetLastError());
Sleep(1000);
}
else if(iRecv == 0)
{
printf("iRecv = 0\n");
}
else
{
printf("%s\n",recv_buf);
}
}
closesocket(sSocket);
WSACleanup();
}