Asynchronous Socket losing connection

I'm trying to develop socket based application on wp7 (client) and WPF (server) and I have issue that I don't understand.

I've written "Server" class which should handle connecting with client and recieving strings.

The problem is that server recieving just first string sent by client and then the connection is breaking, I have to reset my client app (only client). I'm assuming it's server side problem because I'm rewriting server application using Async calls. Before that client works well. My server side code:

public class StateObject
    {
        public byte[] Buffer { get; set; }
        public Socket WorkSocket { get; set; }
    }

    public class MessageRecievedEventArgs : EventArgs
    {
        public string Message { get; set; }
    }

    public class Server
    {
        ManualResetEvent _done;
        TcpListener _listener;

        public event EventHandler<MessageRecievedEventArgs> OnMessageRecieved;
        public Server()
        {
            _done = new ManualResetEvent(false);
            _listener = new TcpListener(IPAddress.Any, 4124);
        }

        public void Start()
        {
            Thread th = new Thread(StartListening);
            th.IsBackground = true;
            th.Start();
        }

        private void StartListening()
        {
            _listener.Start();
            while (true)
            {
                _done.Reset();
                _listener.BeginAcceptTcpClient(new AsyncCallback(OnConnected), _listener);
                _done.WaitOne();
            }

        }
        private void OnConnected(IAsyncResult result)
        {
            TcpListener listener = result.AsyncState as TcpListener;
            Socket socket = listener.EndAcceptSocket(result);
            byte[] buffer = new byte[256];
            StateObject state = new StateObject { Buffer = buffer, WorkSocket = socket };
            socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(OnRead), state);
        }

        private void OnRead(IAsyncResult result)
        {
            var state = (StateObject)result.AsyncState;
            int buffNum = state.WorkSocket.EndReceive(result);
            string message = Encoding.UTF8.GetString(state.Buffer, 0, buffNum);
            if (OnMessageRecieved != null)
            {
                MessageRecievedEventArgs args = new MessageRecievedEventArgs();
                args.Message = message;
                OnMessageRecieved(this, args);
            }
            _done.Set();
        }
    }

Client:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                _socketEventArgs = new SocketAsyncEventArgs() { RemoteEndPoint = App.Connection.RemoteEndPoint };
                Send("{ECHO}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void Send(string key)
        {
            var bytes = Encoding.UTF8.GetBytes(key + "$");
            _socketEventArgs.SetBuffer(bytes, 0, bytes.Count());
            if (Socket.Connected)
                Socket.SendAsync(_socketEventArgs);
            else
                MessageBox.Show("Application is not connected. Please reset connection (press 'back' key and 'connect' button). It may be needed to restart server application"); 
        }

The "{ECHO}" message is sent by client and recieved by server - each next is sent, but not recieved. I assuming that I don't understand sockets async calls mechanism... can someone enlighten me? :)

Answers


It seems like you are only reading once. Probably you want to call read repeatedly to deplete the entire stream.


Need Your Help

Where to store minor user data types when implementing DI/IoC

c# .net design-patterns dependency-injection

There's a same question I keep asking myself each time a new Dependency Injection based solution is being started. I usually have a dedicated assembly for interfaces - this one is referenced by ea...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.