コード例 #1
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try {
                EndPoint sender    = new IPEndPoint(IPAddress.Any, 0);
                var      bytesRead = _socket.EndReceiveFrom(ar, ref sender);

                if (bytesRead > 0)
                {
                    var bytes = new byte[bytesRead];
                    Buffer.BlockCopy(_buffer, 0, bytes, 0, bytesRead);
                    var message = _messageSerializer.Deserialize(bytes);

                    // refactor this (to other layer?)
                    message.RemoteAddress = ((IPEndPoint)sender).Address.ToString();
                    message.Port          = ((IPEndPoint)sender).Port;

                    OnReceive(message);
                    _socket.BeginReceiveFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref sender, ReceiveCallback, null);
                }
            }
            catch (Exception e) {
                OnError(new TransportLayerException(string.Format("receive message error: {0}", e.Message)));
            }
        }