Hi,
I have a simple implementation of UDP based client - server communication using CAsyncSocket class.
.h file:
#if _MSC_VER > 1000
#pragma once
#endif
#include <afxtempl.h>
class UdpReceiveSocket : public CAsyncSocket
{
void OnReceive(int nErrorCode);
public:
UdpReceiveSocket();
virtual ~UdpReceiveSocket();
void SetParent(CDialog* pWnd);
private:
CDialog* m_pWnd;
};
.cpp file:
#include "stdafx.h"
#include "UdpReceiveSocket.h"
#include "ServerDlg.h"
UdpReceiveSocket::UdpReceiveSocket()
{
BOOL bRet = Create(MASTER_PORT, SOCK_DGRAM, FD_READ);
if (bRet != TRUE)
{
UINT uErr = GetLastError();
TCHAR szError[256];
wsprintf(szError, "Server Receive Socket Create() failed: %d", uErr);
AfxMessageBox(szError);
}
}
UdpReceiveSocket::~UdpReceiveSocket()
{
}
void UdpReceiveSocket::OnReceive(int nErrorCode)
{
TCHAR buff[CMAXLENBUFF];
int nRead;
CString strSendersIp;
UINT uSendersPort;
nRead = ReceiveFromEx(buff, CMAXLENBUFF, strSendersIp, uSendersPort);
switch (nRead)
{
case 0: Close();
break;
case SOCKET_ERROR:
if (GetLastError() != WSAEWOULDBLOCK)
{
AfxMessageBox ("UDP Read Error occurred");
Close();
}
break;
default: buff[nRead] = 0;
if (((CServerDlg*)m_pWnd)->commuse == 2)
{
((CServerDlg*)m_pWnd)->m_hcrecv.SetPing(50); ((CServerDlg*)m_pWnd)->IncomingMessage (buff, strSendersIp);
CString tt;
tt.Format ("Received %d bytes, error code: %d", nRead, nErrorCode);
((CServerDlg*)m_pWnd)->Status (tt);
}
}
CAsyncSocket::OnReceive(nErrorCode);
}
void UdpReceiveSocket::SetParent(CDialog *pWnd)
{
m_pWnd = pWnd; }
And I use it like that:
protected:
UdpReceiveSocket m_UDPReceiveSocket; UdpSendSocket m_UDPSendSocket;
BOOL CServerDlg::UDPConnectionInitialise(void)
{
CString con;
m_UDPReceiveSocket.SetParent(this);
con.Format("Connected via UDP port %d", MASTER_PORT);
Status(con);
m_status.SetLed(0,1); return 1;
}
My 'client' is Arduino board with simple software which forwards serial comms to Ethernet port and vice versa. Ethernet port from Arduino is connected to router with Ethernet cable.
My 'server' is my laptop, connected to the same router over Wi-Fi. On the laptop I have software to read the data, using the code above.
Everything was working OK while I was using my old BT router (BT2700HGV). But yesterday I tried it with new TP-Link router (TL-WR841N) and my code isn't working. What happens is, every time new message arrives, it takes long time for ReceiveFromEx() function to return the incoming data (about 5 sec). During this time whole application is blocked. Also next message arrives in the meantime, so as soon as the ReceiveFromEx() returns, it is triggered again.
All this happens only with the new router. I tried to change various settings on it, but nothing has changed this behavior.
I ran 'UDP Test Tool' on the laptop to see if the incoming UDP packets are any different but it looks exactly the same with both routers.
Can anybody help?