异步套接字丢失连接

时间:2012-09-10 18:14:20

标签: wpf windows-phone-7 sockets

我正在尝试在wp7(客户端)和WPF(服务器)上开发基于套接字的应用程序,我遇到了一些我不明白的问题。

我写过“Server”类,它应该处理与客户端和接收字符串的连接。

问题是服务器收到客户端发送的第一个字符串,然后连接断开,我必须重置我的客户端应用程序(只有客户端)。我假设它是服务器端问题,因为我正在使用异步调用重写服务器应用程序。在那之前客户运作良好。我的服务器端代码:

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();
        }
    }

客户端:

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"); 
        }

“{ECHO}”消息由客户端发送并由服务器接收 - 每个消息都被发送,但未收到。我假设我不了解套接字异步调用机制...有人可以启发我吗? :)

1 个答案:

答案 0 :(得分:0)

好像你只读了一次。可能你想反复调用read来耗尽整个流。