Question

I currently have a client-server application that involves a Silverlight client and a .NET server. The .NET portion uses the Tcp classes provided in System.Net.Sockets namespace whereas the Silverlight client uses raw sockets. I'm porting into this from code that currently uses the HttpListener classes because it doesn't suit my needs. The Http classes, though, have on the SL side the ability to use Begin* and End* style asynchronous methods that allow me to specify a handler once the operation has completed. I'm having trouble getting this to work with the new system. My current strategy is to include the handler as part of the UserToken. However, it seems that this token is not getting updated.

Here is some redacted code. I am able to get the two sides to talk to each other, but it seems the correct UserToken is not being sent.

public class ClientUserToken
{
    public Handler Handler { get; set; }
    public string Test { get; set; }

    public ClientUserToken(Handler handler, string test)
    {
        Handler = handler;
        Test = test;
    }
}

public class SocketClient
{
    private Socket _clientSocket;
    private string _ipAddress;
    private int _port;

    private void OpenSocket()
    {
        var endPoint = new DnsEndPoint(_ipAddress, _port);

        SocketAsyncEventArgs args = new SocketAsyncEventArgs();
        args.UserToken = new ClientUserToken(null, "foo");
        args.RemoteEndPoint = endPoint;
        args.Completed += OnSocketCompleted;

        _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _clientSocket.ConnectAsync(args);
    }

    void OnSocketCompleted(object sender, SocketAsyncEventArgs e)
    {
        switch (e.LastOperation)
        {
            case SocketAsyncOperation.Connect: ProcessConnect(e); break;
            case SocketAsyncOperation.Receive: ProcessReceive(e); break;
            case SocketAsyncOperation.Send: ProcessSend(e); break; // this never gets called
        }
    }

    void ProcessConnect(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            byte[] response = new byte[1024];
            e.SetBuffer(response, 0, response.Length);
            _clientSocket.ReceiveAsync(e);
        }
    }

    void ProcessReceive(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
        {
            var userToken = e.UserToken as ClientUserToken; // this token is always the one set in ProcessConnect

            // process the data

            if (!_clientSocket.ReceiveAsync(e))
            {
                ProcessReceive(e);
            }
        }
    }

    // this is never called, for some reason
    void ProcessSend(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            var userToken = e.UserToken as ClientUserToken;

            if (!_clientSocket.ReceiveAsync(e))
            {
                ProcessReceive(e);
            }
        }
    }

    // this is the public API that users use to actually send data across
    public void SendToServer(byte[] data, int len, Handler handler)
    {
        SocketAsyncEventArgs args = new SocketAsyncEventArgs();

        args.UserToken = new ClientUserToken(handler, "bar");
        args.SetBuffer(data, 0, len);

        if (!_clientSocket.SendAsync(args))
        {
            ProcessReceive(args);
        }
    }
}

As the comments above suggest, in ProcessReceive, userToken.Test is always "foo" and userToken.Handler is always null.

I have so far not been able to break into ProcessSend so I can't see what SocketAsyncEventArgs it actually sent. Anyone have a clue why this event isn't firing (Completed after a Send)? Am I screwing up my SendToServer function?

I realize there may be other existing problems with synchronization and such, but I don't think that's the issue here. One thing I did try was setting up a ManualResetEvent to ensure that no one sends data to the server before the connection has been completed (ProcessConnect) but that did not solve the issue, either.

Any help will be appreciated!

EDIT: So the reason this is happening is because when I call ReceiveAsync in the ProcessConnect function, it is being used when the server is sending back the response for my data. Hence, UserToken "foo" is present in the handler. The next time the server sends data, the ReceiveAsync uses the args with the UserToken "bar". So it is kind of out of sync, for the duplex communication bit. I can't ensure that the SocketAsyncEventArgs that I sent from the client-side is the same one that is used on the response. It seems like the only solution is to have the SL client open two sockets--one for server-initiated data and the other for client-initiated requests. However, this means I'm not taking advantage of the duplex nature.

Was it helpful?

Solution

This model won't work because I'm creating a new SocketAsyncEventArgs on each send, which means that the data can come back on any of these args. I've been moving towards a model with a pool of SocketAsyncEventArgs and each client can only have one request/response at a time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top