Vignesh
Vignesh

Reputation: 3601

C# Socket stops receiving

I'm creating a Server Socket in C# for my Unity Application. I have created Asynchronous Server Socket from below link Asynchronous Server Socket

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

public class NetworkStateObject
{
        // Client socket.  
        public Socket workSocket = null;
        // Size of receive buffer.  
        public const int BufferSize = 1024;
        // Receive buffer.  
        public byte[] buffer = new byte[BufferSize];
        // Received data string.  
        public List<byte> receivedBytes = new List<byte>();
}

private readonly ManualResetEvent allDone = new ManualResetEvent(false);
private readonly ManualResetEvent receiveDone = new ManualResetEvent(false);
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 ReceiveData(Socket socket)
    {
        try
        {
            // Create the state object.  
            NetworkStateObject state = new NetworkStateObject();
            state.workSocket = socket;

        // Begin receiving the data from the remote device.  
        socket.BeginReceive(state.buffer, 0, NetworkStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    }
    catch (Exception e)
    {
        Debug.Log(e.ToString());
    }
}

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));
            var bytesArray = state.buffer;
            if (bytesRead < NetworkStateObject.BufferSize)
            {
                Array.Resize(ref bytesArray, bytesRead);
            }
            var bytesList = new List<byte>(bytesArray);
            state.receivedBytes.AddRange(bytesList);

            var receivedBytes = state.receivedBytes;
            var bytesCount = receivedBytes.Count;
            if (receivedBytes.Count > 1)
            {
                var receivedString = Encoding.ASCII.GetString(receivedBytes.ToArray(), 0, bytesCount);
                if (receivedString.IndexOf(receiveDelimitter, StringComparison.CurrentCulture) > -1)
                {
                    var message = receivedString.Replace(receiveDelimitter, String.Empty);
                    message = Regex.Unescape(message);
                    socketBaseDelegate.ReceivedMessage(message);
                    state.receivedBytes.Clear();
                    receiveDone.Set();
                }
                else
                {
                    // Get the rest of the data.
                    socket.BeginReceive(state.buffer, 0, NetworkStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                }
            }
        }
        else
        {
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Debug.Log(e.ToString());
    }
}

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.

Upvotes: 0

Views: 292

Answers (1)

Felix Castor
Felix Castor

Reputation: 1675

else
{
  // Get the rest of the data.
  socket.BeginReceive(state.buffer, 0, NetworkStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}

This part shouldn't be conditional. You should always begin receiving again once the receive callback is complete. Unless of course the connection is terminated.

Upvotes: 0

Related Questions