none
C# Socket stops receiving RRS feed

  • Question

  • I'm creating a Server Socket in C# for my Unity Application by referring Asynchronous Server Socket example from Microsoft docs.

    Using which I can successfully able to connect with client and receive data from client. But after few data received the socket is not receiving data even though the client is sending the data (I'm testing client and server in same machine).

    Also there was no exception thrown in try catch either. So I'm not able to identify the root cause.

    Please find my code below

    private readonly string receiveDelimitter = "<EOF>"; socketThread = new Thread(new ThreadStart(StartSocketServer)); socketThread.Priority = System.Threading.ThreadPriority.BelowNormal; socketThread.IsBackground = true; socketThread.Start(); protected void Receive(Socket socket) { ReceiveData(socket); receiveDone.WaitOne(); }

    private void ReceiveCallback(IAsyncResult ar)
    {
        [...]
                        socketBaseDelegate.ReceivedMessage(message);
        [...]                
    }

    In my controller

    public void ReceivedMessage(string data)
        {
            socketInputParser.Parse(data);
            asynchronousSocketListener.ReceiveMessage();
        }

    In the above code the ReceiveCallback is not triggered after some time. Even though client sends data.

    Monday, December 10, 2018 7:02 AM

All replies

  • There's not nearly enough information here to do any kind of diagnosis.  Have you added debug prints so you can tell how far it gets and where it gets stuck?  My first guess would be that your ReceiveCallback sometimes exits without firing the receiveDone event, so you're blocking there forever.  Or, are you perhaps receiving two callbacks before you can handle the first?

    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Tuesday, December 11, 2018 2:29 AM
  • Hi jvigneshcs,

    Thank you for posting here.

    For your question, I want to confirm some questions with you.

    The socketInputParser  and asynchronousSocketListener method have some definitions you do not provided.

    Please provide all relevant code for Client and Server.We could not test the code, please provide more details.

    Best regards,

    Jack J Jun.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 11, 2018 7:55 AM
    Moderator
  • First I'm not able to post the complete source code as there was restriction in the body length.

    It get stopped at below method

    private void ReceiveData(Socket socket)
        {
            try
            {
                // Create the state object.  
                NetworkStateObject state = new NetworkStateObject();
                state.workSocket = socket;
    
                // Begin receiving the data from the remote device.  
                Debug.Log("AsynchronousSocketBase: Gonna receive data from client.");
                socket.BeginReceive(state.buffer, 0, NetworkStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
    After this ReceiveCallback is not getting called.

    Tuesday, December 11, 2018 9:20 AM
  • Hi jvigneshcs,

    Thank you for posting here.

    For your question, I want to confirm some questions with you.

    Is your ReceiveCallback method the same as the instance on MSDN, if not, please provide the modified information.You can remove the method body of the ReceiveCallback method to see if it works the same as the previous one.Please provide as much code as possible to solve your problem.

    Best regards,

    Jack J Jun.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, December 13, 2018 12:58 AM
    Moderator
  • Hi Jack,

    Thanks for your support,

    private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket   
                // from the asynchronous state object.  
                NetworkStateObject state = (NetworkStateObject)ar.AsyncState;
                Socket socket = state.workSocket;
    
                // Read data from the remote device.  
                int bytesRead = socket.EndReceive(ar);
    
                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.  
                    //state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    if (lastPartialMessageRecedived != null)
                    {
                        state.stringBuilder.Append(lastPartialMessageRecedived);
                        lastPartialMessageRecedived = null;
                    }
                    state.stringBuilder.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
    
                    var receivedString = state.stringBuilder.ToString();
                    if (receivedString.EndsWith(receiveDelimitter, StringComparison.CurrentCulture))
                    {
                        Debug.Log("AsynchronousSocketBase: Message received from client - " + receivedString);
                        var commands = receivedString.Split(receiveDelimitter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        var commandList = new List<string>(commands);
                        var unescapedCommands = UnescapedSrtings(commandList);
                        socketBaseDelegate.ReceivedMessages(unescapedCommands);
    
                        receiveDone.Set();
                    }
                    else if (receivedString.IndexOf(receiveDelimitter, StringComparison.CurrentCulture) > -1)
                    {
                        var commands = receivedString.Split(receiveDelimitter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        var commandList = new List<string>(commands);
                        var commandCount = commandList.Count;
                        var lastIndex = commandCount - 1;
                        lastPartialMessageRecedived = commandList[lastIndex];
                        commandList.RemoveAt(lastIndex);
                        Debug.Log("AsynchronousSocketBase: Stringbuilder after reset - " + lastPartialMessageRecedived);
    
                        var unescapedCommands = UnescapedSrtings(commandList);
                        socketBaseDelegate.ReceivedMessages(unescapedCommands);
    
                        receiveDone.Set();
                    }
                    else
                    {
                        // Get the rest of the data.
                        socket.BeginReceive(state.buffer, 0, NetworkStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                    }
                }
                else
                {
                    Debug.Log("AsynchronousSocketBase: Receive done set");
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }

    private List<string> UnescapedSrtings(List<string> list)
        {
            List<string> unescaped = new List<string>();
            foreach(string item in list)
            {
                var text = Regex.Unescape(item);
                unescaped.Add(text);
            }
            return unescaped;
        }

    Thursday, December 13, 2018 11:48 AM
  • Hi jvigneshcs,

    Thank you for posting here.

    For your question, I want to confirm some questions with you.

    I think you are missing the following code: the definition of lastPartialMessageRecedived, the definition of receiveDelimitter, and the definition of socketBaseDelegate.ReceivedMessages.

    Please provide these details and we are waiting for your update.

    Best regards,

    Jack J Jun.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, December 14, 2018 9:41 AM
    Moderator
  • Hi Jack,

    Please find the code below,

    // Socket Base Delegate Listener public void ReadyToRead() { asynchronousSocketListener.ReceiveMessage(); } public void ReceivedMessages(List<string> data) { asynchronousSocketListener.ReceiveMessage(); }

    // AsyncronousSocketListener
    private Socket clientRequestHandler;
    private readonly string receiveDelimitter = "<EOF>";
    private string lastPartialMessageRecedived;
    private readonly ManualResetEvent receiveDone = new ManualResetEvent(false);
    
    private void StartSocketServer() {
            // Establish the local endpoint for the socket.  
            // The DNS name of the computer  
            // running the listener is "localhost". 
    
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, ConnectedPort);
    
            // Create a TCP/IP socket.  
            listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            // Bind the socket to the local endpoint and listen for incoming connections.  
            try {
                listener.Bind(localEndPoint);
                listener.Listen(100);
                serverSocketDelegate.SocketListening(ipAddress, ConnectedPort);
                while (true) {
                    // Set the event to nonsignaled state.  
                    allDone.Reset();
    
                    // Start an asynchronous socket to listen for connections.  
                    Debug.Log("Waiting for a connection...");
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
    
                    // Wait until a connection is made before continuing.  
                    allDone.WaitOne();
                }
            } catch (Exception e) {
                serverSocketDelegate.ListeningFailed(e.ToString());
                Debug.Log(e.ToString());
            }
        }
    
    private void AcceptCallback(IAsyncResult ar) {
            // Signal the main thread to continue.  
            allDone.Set();
    
            // Get the socket that handles the client request.  
            Socket socket = (Socket)ar.AsyncState;
            clientRequestHandler = socket.EndAccept(ar);
            serverSocketDelegate.ReadyToRead();
        }
    
    
    public override void ReceiveMessage() {
            // Receive the response from the remote device.  
            Receive(clientRequestHandler);
        }
    
    protected void Receive(Socket socket) {
            ReceiveData(socket);
            receiveDone.WaitOne();
        }
    
    private void ReceiveData(Socket socket) {
            try {
                // Create the state object.  
                NetworkStateObject state = new NetworkStateObject();
                state.workSocket = socket;
    
                // Begin receiving the data from the remote device.  
                Debug.Log("AsynchronousSocketBase: Gonna receive data from client.");
                socket.BeginReceive(state.buffer, 0, NetworkStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
            } catch (Exception e) {
                Debug.Log(e.ToString());
            }
        }



    • Edited by jvigneshcs Friday, December 14, 2018 12:11 PM Added more code
    Friday, December 14, 2018 12:09 PM
  • Hi jvigneshcs,

    For your question, you want to know why socket stops receiving data.

    Please refer to the link below.

    https://stackoverflow.com/questions/24019512/socket-stops-receiving-new-data

    Best regards,

    Jack J Jun.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 18, 2018 7:27 AM
    Moderator
  • Hi Jack,

    Even I have tried Thread.Sleep() but still the result is same. Please find the updated code below,

    protected void Receive(Socket socket)
        {
            ReceiveData(socket);
            receiveDone.WaitOne();
            Thread.Sleep(500);
        }


    • Edited by jvigneshcs Tuesday, December 18, 2018 10:10 AM
    Tuesday, December 18, 2018 10:10 AM
  • Hi jvigneshcs,

    According to your code, you could set Thread.Sleep() in your client code instead of server code.

    Best regards,

    Jack J Jun.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, December 19, 2018 2:24 AM
    Moderator
  • Hi Jack,

    Yes we are calling sleep even in our client code, but in server we just tried and removed sleep.

    Our client code is in Python, we make it sleep after sending data using following code,

    time.sleep(0.5)

    Wednesday, December 19, 2018 5:17 AM