Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8994519
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T23:27:02+00:00 2026-06-15T23:27:02+00:00

I am trying to use Socket.BeginReceive(…) and Socket.EndReceive(…) as my UDP Packet Receiver client.

  • 0

I am trying to use Socket.BeginReceive(…) and Socket.EndReceive(…) as my UDP Packet Receiver client. It receives and processes packets as expected, however, when I wish to cancel and shutdown the socket, my implemented Close() function exits on Socket.EndReceive(…). I assume an exception was thrown on the thread but I cannot figure out how to catch the exception to see what the problem is. I have used Socket.EndReceive(…) before with the SocketError returning as Success. Here is a bit of code that shows how I’m using the socket.

Updated Code

void _startReceiving()
{
    _buffer = new byte[Marshal.SizeOf(typeof(EthernetShare.Message))];
    _receiveResult = _udpSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, messageProcessor, null);
}

private void messageProcessor(IAsyncResult result)
{
    int packetSize = _udpSocket.EndReceive(result);
    if (packetSize == _buffer.Length)
    {
        byte[] packet = _buffer;
        IAsyncResult asyncResult = result;
        _startReceiving();
        OnMessageReceieved(_buffer.ToStruct<DataStreamingMessage>());
    }
}
public void Stop()
{

    _continue = false;
    SocketError error;
    try
    {
        int tmp = _udpSocket.EndReceive(_receiveResult, out error);

    }
    catch (Exception)
    {

        throw;
    }
    _udpSocket.Close();
}

Old Code

private Socket _udpSocket;
private byte[] _buffer;
private IAsyncResult _receiveResult;
void _startReceiving()
{
    byte[] buffer = new byte[Marshal.SizeOf(typeof(EthernetShare.Message))];
    _receiveResult = _udpSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, messageProcessor, null);
    //_receiveResult = _udpSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, messageProcessor, _continue);
}

private void messageProcessor(IAsyncResult result)
{

    //if ((bool)result.AsyncState && result.IsCompleted)
    if (result.IsCompleted)
    {
        _buffer = new byte[Marshal.SizeOf(typeof (EthernetShare.Message))];
        //_receiveResult = _udpSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, messageProcessor, _continue);
        _receiveResult = _udpSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, messageProcessor, null);
    }
}


public void Stop()
{

    _continue = false;
    SocketError error;
    try
    {
        int tmp = _udpSocket.EndReceive(_receiveResult, out error);

    }
    catch (Exception)
    {

        throw;
    }
    _udpSocket.Close();
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T23:27:03+00:00Added an answer on June 15, 2026 at 11:27 pm

    Your use of APM (Asynchronous Programming Model) is wrong. See: http://msdn.microsoft.com/en-us/library/ms228963.aspx

    Each call to BeginXXX should be matched with an EndXXX.

    In pseudo code, it might look something like this:

    private bool isClosed;
    private Socket socket;
    
    void BeginReceiveNextPacket(){
        socket.BeginReceive(..., EndReceiveNextPacket);
    }
    
    void EndReceiveNextPacket(IAsyncResult result){
        try{
            // By making a call to EndReceive, we allow the socket to wrap up, close internal handles and raise any exceptions if they exist.
            socket.EndReceive(result); 
    
            // Now make a new call to BeginReceive after we invoked the actual call to EndReceive.
            BeginReceiveNextPacket();
        }
        catch(SocketClosedException) {
            if (closed){
                // We forcefully closed this socket. Therefore, this exception was expected and we can ignore it.
            }
            else{
                throw; // Catch an unexpected exception.
            }
        }
    }
    
    void Stop(){
        isClosed = true;
        socekt.Close();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to use python socket instead of netcat to send metric data
I am trying to use the code from Microsoft for an Async Socket connection.
I am trying to use a self-signed certificate in a ssl socket on windows8
Creating a server-side socket will fail if I'm trying to use the same port
I am getting start to socket use in C programming language. I am trying
In what situations should i use Socket class or XMLSocket when trying to connect
I'm trying to use Moles to mock the Socket class in System.Net.Sockets. I have
I was trying to use a struct to parse socket data when implement a
Hezy, Im trying to use socket programming, I need a background service. I tried
For example, let's say we're trying to use socket.io. In the html file served

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.