Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hallo Everyone,



I have a program which can receive udp packets continuously from the server,
but how can i check new packet is received ufrom the server?

My program for receiving udp packet i have written below.


if anyone has idea about it , please do share!
Thanks in addvance


cheers!

What I have tried:

TCP Socket class
.cpp file

void UdpReceivingSocket::OnReceive(int nErrorCode)
{
nRead = Receive(buff, 4096); 
	icount1++;

	switch (nRead)
	{
	case 0:       // Connection was closed.
		Close();
		break;
	case SOCKET_ERROR:
		if (GetLastError() != WSAEWOULDBLOCK)
		{
			AfxMessageBox(L"Error occurred");
			Close();
		}
		break;

	default: // Normal case: Receive() returned the # of bytes received.
		
		buff[nRead] = 0;

CAsyncSocket::OnReceive(nErrorCode);
}

.h file
#pragma once
#include <afxsock.h>

#include "FILE_TRIALDlg.h"
# include "TcpSendSocket.h"


class UdpReceivingSocket :
	public CAsyncSocket
{
	
	void OnReceive(int nErrorCode);
public:

	UdpReceivingSocket();
	~UdpReceivingSocket();
	BYTE buff[4096];
	int nRead;

};
Posted
Updated 29-Jul-19 12:02pm
Comments
[no name] 29-Jul-19 10:18am    
E.g. in OnReceive you can send a windows message to a specific (maybe hidden) window. In case you do that, make sure to use PostMessage and _never_ SendMessage
Richard MacCutchan 29-Jul-19 10:27am    
What do you mean how can I check"? You get a notification in the OnReceive function. But in order to know what part of the sender message is received you need to set a message protocol between the server and client, so each end knows when a new message is being received. For example adding a message header which gives the message length tells the receiver how many bytes to accept for a complete message.
KarstenK 29-Jul-19 12:25pm    
udp is a bit unreliable, because its connection is stateless. Consider using tcp.
Member 14499788 30-Jul-19 5:20am    
Problem is solved!!!
I used a counter for the socket class.

Thanks all for the suggestions!
I really appreciate all of you here for help people like us who are beginners.
Great work!!
cheers

1 solution

You can check by looking at how many bytes the Receive function returns. If it's greater than zero then you have received a message. At that point, this method could call method to process the message or set a flag so something else knows that it needs to.

There is no need or sense in adding a zero to the buffer. If the message contains textual data that should be terminated with a null then you should send the null character with the data so it is self-contained. If the message is not textual data then it certainly doesn't need anything added to it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900